@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 bp=Object.create;var Mc=Object.defineProperty;var kp=Object.getOwnPropertyDescriptor;var Sp=Object.getOwnPropertyNames;var Ep=Object.getPrototypeOf,xp=Object.prototype.hasOwnProperty;var Oi=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var N=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Cp=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Sp(t))!xp.call(e,n)&&n!==r&&Mc(e,n,{get:()=>t[n],enumerable:!(i=kp(t,n))||i.enumerable});return e};var kr=(e,t,r)=>(r=e!=null?bp(Ep(e)):{},Cp(t||!e||!e.__esModule?Mc(r,"default",{value:e,enumerable:!0}):r,e));var P=w(W=>{"use strict";var Ga=Symbol.for("yaml.alias"),Fc=Symbol.for("yaml.document"),Hi=Symbol.for("yaml.map"),qc=Symbol.for("yaml.pair"),Ua=Symbol.for("yaml.scalar"),Di=Symbol.for("yaml.seq"),Fe=Symbol.for("yaml.node.type"),Pp=e=>!!e&&typeof e=="object"&&e[Fe]===Ga,Rp=e=>!!e&&typeof e=="object"&&e[Fe]===Fc,Ap=e=>!!e&&typeof e=="object"&&e[Fe]===Hi,_p=e=>!!e&&typeof e=="object"&&e[Fe]===qc,Wc=e=>!!e&&typeof e=="object"&&e[Fe]===Ua,Ip=e=>!!e&&typeof e=="object"&&e[Fe]===Di;function zc(e){if(e&&typeof e=="object")switch(e[Fe]){case Hi:case Di:return!0}return!1}function Tp(e){if(e&&typeof e=="object")switch(e[Fe]){case Ga:case Hi:case Ua:case Di:return!0}return!1}var jp=e=>(Wc(e)||zc(e))&&!!e.anchor;W.ALIAS=Ga;W.DOC=Fc;W.MAP=Hi;W.NODE_TYPE=Fe;W.PAIR=qc;W.SCALAR=Ua;W.SEQ=Di;W.hasAnchor=jp;W.isAlias=Pp;W.isCollection=zc;W.isDocument=Rp;W.isMap=Ap;W.isNode=Tp;W.isPair=_p;W.isScalar=Wc;W.isSeq=Ip});var Sr=w(Ka=>{"use strict";var V=P(),X=Symbol("break visit"),Jc=Symbol("skip children"),Ie=Symbol("remove node");function Bi(e,t){let r=Gc(t);V.isDocument(e)?qt(null,e.contents,r,Object.freeze([e]))===Ie&&(e.contents=null):qt(null,e,r,Object.freeze([]))}Bi.BREAK=X;Bi.SKIP=Jc;Bi.REMOVE=Ie;function qt(e,t,r,i){let n=Uc(e,t,r,i);if(V.isNode(n)||V.isPair(n))return Kc(e,i,n),qt(e,n,r,i);if(typeof n!="symbol"){if(V.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=qt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Ie&&(t.items.splice(a,1),a-=1)}}}else if(V.isPair(t)){i=Object.freeze(i.concat(t));let a=qt("key",t.key,r,i);if(a===X)return X;a===Ie&&(t.key=null);let o=qt("value",t.value,r,i);if(o===X)return X;o===Ie&&(t.value=null)}}return n}async function Li(e,t){let r=Gc(t);V.isDocument(e)?await Wt(null,e.contents,r,Object.freeze([e]))===Ie&&(e.contents=null):await Wt(null,e,r,Object.freeze([]))}Li.BREAK=X;Li.SKIP=Jc;Li.REMOVE=Ie;async function Wt(e,t,r,i){let n=await Uc(e,t,r,i);if(V.isNode(n)||V.isPair(n))return Kc(e,i,n),Wt(e,n,r,i);if(typeof n!="symbol"){if(V.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Wt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Ie&&(t.items.splice(a,1),a-=1)}}}else if(V.isPair(t)){i=Object.freeze(i.concat(t));let a=await Wt("key",t.key,r,i);if(a===X)return X;a===Ie&&(t.key=null);let o=await Wt("value",t.value,r,i);if(o===X)return X;o===Ie&&(t.value=null)}}return n}function Gc(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Uc(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(V.isMap(t))return r.Map?.(e,t,i);if(V.isSeq(t))return r.Seq?.(e,t,i);if(V.isPair(t))return r.Pair?.(e,t,i);if(V.isScalar(t))return r.Scalar?.(e,t,i);if(V.isAlias(t))return r.Alias?.(e,t,i)}function Kc(e,t,r){let i=t[t.length-1];if(V.isCollection(i))i.items[e]=r;else if(V.isPair(i))e==="key"?i.key=r:i.value=r;else if(V.isDocument(i))i.contents=r;else{let n=V.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ka.visit=Bi;Ka.visitAsync=Li});var Ya=w(Xc=>{"use strict";var Yc=P(),$p=Sr(),Op={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hp=e=>e.replace(/[!,[\]{}]/g,t=>Op[t]),Er=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Hp(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Yc.isNode(t.contents)){let a={};$p.visit(t.contents,(o,s)=>{Yc.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};Er.defaultYaml={explicit:!1,version:"1.2"};Er.defaultTags={"!!":"tag:yaml.org,2002:"};Xc.Directives=Er});var Vi=w(xr=>{"use strict";var Qc=P(),Dp=Sr();function Bp(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Zc(e){let t=new Set;return Dp.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function el(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Lp(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Zc(e));let o=el(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Qc.isScalar(o.node)||Qc.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}}xr.anchorIsValid=Bp;xr.anchorNames=Zc;xr.createNodeAnchors=Lp;xr.findNewAnchor=el});var Xa=w(tl=>{"use strict";function Cr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Cr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Cr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Cr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Cr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}tl.applyReviver=Cr});var tt=w(il=>{"use strict";var Vp=P();function rl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>rl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Vp.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}il.toJS=rl});var Mi=w(al=>{"use strict";var Mp=Xa(),nl=P(),Fp=tt(),Qa=class{constructor(t){Object.defineProperty(this,nl.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!nl.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Fp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Mp.applyReviver(a,{"":s},"",s):s}};al.NodeBase=Qa});var Pr=w(ol=>{"use strict";var qp=Vi(),Wp=Sr(),zt=P(),zp=Mi(),Jp=tt(),Za=class extends zp.NodeBase{constructor(t){super(zt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Wp.visit(t,{Node:(a,o)=>{(zt.isAlias(o)||zt.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Jp.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=Fi(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(qp.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Fi(e,t,r){if(zt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(zt.isCollection(t)){let i=0;for(let n of t.items){let a=Fi(e,n,r);a>i&&(i=a)}return i}else if(zt.isPair(t)){let i=Fi(e,t.key,r),n=Fi(e,t.value,r);return Math.max(i,n)}return 1}ol.Alias=Za});var H=w(eo=>{"use strict";var Gp=P(),Up=Mi(),Kp=tt(),Yp=e=>!e||typeof e!="function"&&typeof e!="object",rt=class extends Up.NodeBase{constructor(t){super(Gp.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Kp.toJS(this.value,t,r)}toString(){return String(this.value)}};rt.BLOCK_FOLDED="BLOCK_FOLDED";rt.BLOCK_LITERAL="BLOCK_LITERAL";rt.PLAIN="PLAIN";rt.QUOTE_DOUBLE="QUOTE_DOUBLE";rt.QUOTE_SINGLE="QUOTE_SINGLE";eo.Scalar=rt;eo.isScalarValue=Yp});var Rr=w(cl=>{"use strict";var Xp=Pr(),Pt=P(),sl=H(),Qp="tag:yaml.org,2002:";function Zp(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function em(e,t,r){if(Pt.isDocument(e)&&(e=e.contents),Pt.isNode(e))return e;if(Pt.isPair(e)){let d=r.schema[Pt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Xp.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Qp+t.slice(2));let l=Zp(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new sl.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Pt.MAP]:Symbol.iterator in Object(e)?o[Pt.SEQ]:o[Pt.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new sl.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}cl.createNode=em});var Wi=w(qi=>{"use strict";var tm=Rr(),Te=P(),rm=Mi();function to(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return tm.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var ll=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ro=class extends rm.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Te.isNode(i)||Te.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(ll(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Te.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,to(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Te.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Te.isScalar(a)?a.value:a:Te.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Te.isPair(r))return!1;let i=r.value;return i==null||t&&Te.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Te.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Te.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,to(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};qi.Collection=ro;qi.collectionFromPath=to;qi.isEmptyPath=ll});var Ar=w(zi=>{"use strict";var im=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function io(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var nm=(e,t,r)=>e.endsWith(`
4
+ var bp=Object.create;var Mc=Object.defineProperty;var kp=Object.getOwnPropertyDescriptor;var Sp=Object.getOwnPropertyNames;var Ep=Object.getPrototypeOf,xp=Object.prototype.hasOwnProperty;var Oi=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var N=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Cp=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Sp(t))!xp.call(e,n)&&n!==r&&Mc(e,n,{get:()=>t[n],enumerable:!(i=kp(t,n))||i.enumerable});return e};var kr=(e,t,r)=>(r=e!=null?bp(Ep(e)):{},Cp(t||!e||!e.__esModule?Mc(r,"default",{value:e,enumerable:!0}):r,e));var P=w(W=>{"use strict";var Ga=Symbol.for("yaml.alias"),Fc=Symbol.for("yaml.document"),Hi=Symbol.for("yaml.map"),qc=Symbol.for("yaml.pair"),Ua=Symbol.for("yaml.scalar"),Di=Symbol.for("yaml.seq"),qe=Symbol.for("yaml.node.type"),Pp=e=>!!e&&typeof e=="object"&&e[qe]===Ga,Rp=e=>!!e&&typeof e=="object"&&e[qe]===Fc,Ap=e=>!!e&&typeof e=="object"&&e[qe]===Hi,_p=e=>!!e&&typeof e=="object"&&e[qe]===qc,Wc=e=>!!e&&typeof e=="object"&&e[qe]===Ua,Ip=e=>!!e&&typeof e=="object"&&e[qe]===Di;function zc(e){if(e&&typeof e=="object")switch(e[qe]){case Hi:case Di:return!0}return!1}function Tp(e){if(e&&typeof e=="object")switch(e[qe]){case Ga:case Hi:case Ua:case Di:return!0}return!1}var jp=e=>(Wc(e)||zc(e))&&!!e.anchor;W.ALIAS=Ga;W.DOC=Fc;W.MAP=Hi;W.NODE_TYPE=qe;W.PAIR=qc;W.SCALAR=Ua;W.SEQ=Di;W.hasAnchor=jp;W.isAlias=Pp;W.isCollection=zc;W.isDocument=Rp;W.isMap=Ap;W.isNode=Tp;W.isPair=_p;W.isScalar=Wc;W.isSeq=Ip});var Sr=w(Ka=>{"use strict";var V=P(),X=Symbol("break visit"),Jc=Symbol("skip children"),Te=Symbol("remove node");function Bi(e,t){let r=Gc(t);V.isDocument(e)?qt(null,e.contents,r,Object.freeze([e]))===Te&&(e.contents=null):qt(null,e,r,Object.freeze([]))}Bi.BREAK=X;Bi.SKIP=Jc;Bi.REMOVE=Te;function qt(e,t,r,i){let n=Uc(e,t,r,i);if(V.isNode(n)||V.isPair(n))return Kc(e,i,n),qt(e,n,r,i);if(typeof n!="symbol"){if(V.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=qt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Te&&(t.items.splice(a,1),a-=1)}}}else if(V.isPair(t)){i=Object.freeze(i.concat(t));let a=qt("key",t.key,r,i);if(a===X)return X;a===Te&&(t.key=null);let o=qt("value",t.value,r,i);if(o===X)return X;o===Te&&(t.value=null)}}return n}async function Li(e,t){let r=Gc(t);V.isDocument(e)?await Wt(null,e.contents,r,Object.freeze([e]))===Te&&(e.contents=null):await Wt(null,e,r,Object.freeze([]))}Li.BREAK=X;Li.SKIP=Jc;Li.REMOVE=Te;async function Wt(e,t,r,i){let n=await Uc(e,t,r,i);if(V.isNode(n)||V.isPair(n))return Kc(e,i,n),Wt(e,n,r,i);if(typeof n!="symbol"){if(V.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Wt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===X)return X;o===Te&&(t.items.splice(a,1),a-=1)}}}else if(V.isPair(t)){i=Object.freeze(i.concat(t));let a=await Wt("key",t.key,r,i);if(a===X)return X;a===Te&&(t.key=null);let o=await Wt("value",t.value,r,i);if(o===X)return X;o===Te&&(t.value=null)}}return n}function Gc(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Uc(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(V.isMap(t))return r.Map?.(e,t,i);if(V.isSeq(t))return r.Seq?.(e,t,i);if(V.isPair(t))return r.Pair?.(e,t,i);if(V.isScalar(t))return r.Scalar?.(e,t,i);if(V.isAlias(t))return r.Alias?.(e,t,i)}function Kc(e,t,r){let i=t[t.length-1];if(V.isCollection(i))i.items[e]=r;else if(V.isPair(i))e==="key"?i.key=r:i.value=r;else if(V.isDocument(i))i.contents=r;else{let n=V.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ka.visit=Bi;Ka.visitAsync=Li});var Ya=w(Xc=>{"use strict";var Yc=P(),$p=Sr(),Op={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hp=e=>e.replace(/[!,[\]{}]/g,t=>Op[t]),Er=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Hp(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Yc.isNode(t.contents)){let a={};$p.visit(t.contents,(o,s)=>{Yc.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};Er.defaultYaml={explicit:!1,version:"1.2"};Er.defaultTags={"!!":"tag:yaml.org,2002:"};Xc.Directives=Er});var Vi=w(xr=>{"use strict";var Qc=P(),Dp=Sr();function Bp(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Zc(e){let t=new Set;return Dp.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function el(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Lp(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Zc(e));let o=el(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Qc.isScalar(o.node)||Qc.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}}xr.anchorIsValid=Bp;xr.anchorNames=Zc;xr.createNodeAnchors=Lp;xr.findNewAnchor=el});var Xa=w(tl=>{"use strict";function Cr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Cr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Cr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Cr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Cr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}tl.applyReviver=Cr});var tt=w(il=>{"use strict";var Vp=P();function rl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>rl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Vp.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}il.toJS=rl});var Mi=w(al=>{"use strict";var Mp=Xa(),nl=P(),Fp=tt(),Qa=class{constructor(t){Object.defineProperty(this,nl.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!nl.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Fp.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Mp.applyReviver(a,{"":s},"",s):s}};al.NodeBase=Qa});var Pr=w(ol=>{"use strict";var qp=Vi(),Wp=Sr(),zt=P(),zp=Mi(),Jp=tt(),Za=class extends zp.NodeBase{constructor(t){super(zt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Wp.visit(t,{Node:(a,o)=>{(zt.isAlias(o)||zt.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Jp.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=Fi(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(qp.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function Fi(e,t,r){if(zt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(zt.isCollection(t)){let i=0;for(let n of t.items){let a=Fi(e,n,r);a>i&&(i=a)}return i}else if(zt.isPair(t)){let i=Fi(e,t.key,r),n=Fi(e,t.value,r);return Math.max(i,n)}return 1}ol.Alias=Za});var H=w(eo=>{"use strict";var Gp=P(),Up=Mi(),Kp=tt(),Yp=e=>!e||typeof e!="function"&&typeof e!="object",rt=class extends Up.NodeBase{constructor(t){super(Gp.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Kp.toJS(this.value,t,r)}toString(){return String(this.value)}};rt.BLOCK_FOLDED="BLOCK_FOLDED";rt.BLOCK_LITERAL="BLOCK_LITERAL";rt.PLAIN="PLAIN";rt.QUOTE_DOUBLE="QUOTE_DOUBLE";rt.QUOTE_SINGLE="QUOTE_SINGLE";eo.Scalar=rt;eo.isScalarValue=Yp});var Rr=w(cl=>{"use strict";var Xp=Pr(),Pt=P(),sl=H(),Qp="tag:yaml.org,2002:";function Zp(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function em(e,t,r){if(Pt.isDocument(e)&&(e=e.contents),Pt.isNode(e))return e;if(Pt.isPair(e)){let d=r.schema[Pt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Xp.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Qp+t.slice(2));let l=Zp(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new sl.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Pt.MAP]:Symbol.iterator in Object(e)?o[Pt.SEQ]:o[Pt.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new sl.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}cl.createNode=em});var Wi=w(qi=>{"use strict";var tm=Rr(),je=P(),rm=Mi();function to(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return tm.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var ll=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ro=class extends rm.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>je.isNode(i)||je.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(ll(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(je.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,to(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(je.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&je.isScalar(a)?a.value:a:je.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!je.isPair(r))return!1;let i=r.value;return i==null||t&&je.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return je.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(je.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,to(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};qi.Collection=ro;qi.collectionFromPath=to;qi.isEmptyPath=ll});var Ar=w(zi=>{"use strict";var im=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function io(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var nm=(e,t,r)=>e.endsWith(`
6
6
  `)?io(r,t):r.includes(`
7
7
  `)?`
8
8
  `+io(r,t):(e.endsWith(" ")?"":" ")+r;zi.indentComment=io;zi.lineComment=nm;zi.stringifyComment=im});var dl=w(_r=>{"use strict";var am="flow",no="block",Ji="quoted";function om(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let f,p,v=!1,h=-1,m=-1,y=-1;r===no&&(h=ul(e,h,t.length),h!==-1&&(d=h+c));for(let S;S=e[h+=1];){if(r===Ji&&S==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}y=h}if(S===`
@@ -11,7 +11,7 @@ var bp=Object.create;var Mc=Object.defineProperty;var kp=Object.getOwnPropertyDe
11
11
  `&&E!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===Ji){for(;p===" "||p===" ";)p=S,S=e[h+=1],v=!0;let E=h>y+1?h-2:m-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else v=!0}p=S}if(v&&s&&s(),l.length===0)return e;o&&o();let b=e.slice(0,l[0]);for(let S=0;S<l.length;++S){let E=l[S],x=l[S+1]||e.length;E===0?b=`
12
12
  ${t}${e.slice(0,x)}`:(r===Ji&&u[E]&&(b+=`${e[E]}\\`),b+=`
13
13
  ${t}${e.slice(E+1,x)}`)}return b}function ul(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}_r.FOLD_BLOCK=no;_r.FOLD_FLOW=am;_r.FOLD_QUOTED=Ji;_r.foldFlowLines=om});var Tr=w(fl=>{"use strict";var Ne=H(),it=dl(),Ui=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ki=e=>/^(%|---|\.\.\.)/m.test(e);function sm(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
14
+ `);i=t,n=t+1,a=e[n]}return i}_r.FOLD_BLOCK=no;_r.FOLD_FLOW=am;_r.FOLD_QUOTED=Ji;_r.foldFlowLines=om});var Tr=w(fl=>{"use strict";var be=H(),it=dl(),Ui=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ki=e=>/^(%|---|\.\.\.)/m.test(e);function sm(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
15
  `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Ir(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Ki(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let 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,28 +20,28 @@ ${t}${e.slice(E+1,x)}`)}return b}function ul(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
20
20
  ${r}`)+"'";return t.implicitKey?i:it.foldFlowLines(i,r,it.FOLD_FLOW,Ui(t,!1))}function Jt(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Ir;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=ao:a&&!n?i=Ir:i=r?ao:Ir}return i(e,t)}var oo;try{oo=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{oo=/\n+(?!\n|$)/g}function Gi({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Jt(r,i);let l=i.indent||(i.forceBlockIndent||Ki(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ne.Scalar.BLOCK_FOLDED?!1:t===Ne.Scalar.BLOCK_LITERAL?!0:!sm(r,c,l.length);if(!r)return u?`|
23
+ |$)`,"g")}catch{oo=/\n+(?!\n|$)/g}function Gi({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Jt(r,i);let l=i.indent||(i.forceBlockIndent||Ki(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===be.Scalar.BLOCK_FOLDED?!1:t===be.Scalar.BLOCK_LITERAL?!0:!sm(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 p=r.substring(f),v=p.indexOf(`
27
27
  `);v===-1?d="-":r===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
28
28
  `&&(p=p.slice(0,-1)),p=p.replace(oo,`$&${l}`));let h=!1,m,y=-1;for(m=0;m<r.length;++m){let x=r[m];if(x===" ")h=!0;else if(x===`
29
29
  `)y=m;else break}let b=r.substring(0,y<m?y+1:m);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let E=(h?l?"2":"1":"")+d;if(e&&(E+=" "+s(e.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}`),g=!1,R=Ui(i,!0);o!=="folded"&&t!==Ne.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{g=!0});let k=it.foldFlowLines(`${b}${x}${p}`,l,it.FOLD_BLOCK,R);if(!g)return`>${E}
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,R=Ui(i,!0);o!=="folded"&&t!==be.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{g=!0});let k=it.foldFlowLines(`${b}${x}${p}`,l,it.FOLD_BLOCK,R);if(!g)return`>${E}
31
31
  ${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${E}
32
32
  ${l}${b}${r}${p}`}function cm(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
33
  `)||u&&/[[\]{},]/.test(a))return Jt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?Jt(a,t):Gi(e,t,r,i);if(!s&&!u&&n!==Ne.Scalar.PLAIN&&a.includes(`
34
+ `)?Jt(a,t):Gi(e,t,r,i);if(!s&&!u&&n!==be.Scalar.PLAIN&&a.includes(`
35
35
  `))return Gi(e,t,r,i);if(Ki(a)){if(c==="")return t.forceBlockIndent=!0,Gi(e,t,r,i);if(s&&c===l)return Jt(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Jt(a,t)}return s?d:it.foldFlowLines(d,c,it.FOLD_FLOW,Ui(t,!1))}function lm(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Ne.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ne.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ne.Scalar.BLOCK_FOLDED:case Ne.Scalar.BLOCK_LITERAL:return n||a?Jt(o.value,t):Gi(o,t,r,i);case Ne.Scalar.QUOTE_DOUBLE:return Ir(o.value,t);case Ne.Scalar.QUOTE_SINGLE:return ao(o.value,t);case Ne.Scalar.PLAIN:return cm(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}fl.stringifyString=lm});var jr=w(so=>{"use strict";var um=Vi(),nt=P(),dm=Ar(),fm=Tr();function hm(e,t){let r=Object.assign({blockQuote:!0,commentString:dm.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function pm(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(nt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function mm(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(nt.isScalar(e)||nt.isCollection(e))&&e.anchor;a&&um.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function vm(e,t,r,i){if(nt.isPair(e))return e.toString(t,r,i);if(nt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=nt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=pm(t.doc.schema.tags,a));let o=mm(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):nt.isScalar(a)?fm.stringifyString(a,t,r,i):a.toString(t,r,i);return o?nt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}so.createStringifyContext=hm;so.stringify=vm});var vl=w(ml=>{"use strict";var qe=P(),hl=H(),pl=jr(),$r=Ar();function gm({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=qe.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(qe.isCollection(e)||!qe.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||qe.isCollection(e)||(qe.isScalar(e)?e.type===hl.Scalar.BLOCK_FOLDED||e.type===hl.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=pl.stringify(e,r,()=>v=!0,()=>h=!0);if(!p&&!r.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=$r.lineComment(m,r.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=$r.lineComment(m,r.indent,l(f))),m=`? ${m}
38
- ${s}:`):(m=`${m}:`,f&&(m+=$r.lineComment(m,r.indent,l(f))));let y,b,S;qe.isNode(t)?(y=!!t.spaceBefore,b=t.commentBefore,S=t.comment):(y=!1,b=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&qe.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&qe.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let E=!1,x=pl.stringify(t,r,()=>E=!0,()=>h=!0),g=" ";if(f||y||b){if(g=y?`
36
+ ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Jt(a,t)}return s?d:it.foldFlowLines(d,c,it.FOLD_FLOW,Ui(t,!1))}function lm(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==be.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=be.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case be.Scalar.BLOCK_FOLDED:case be.Scalar.BLOCK_LITERAL:return n||a?Jt(o.value,t):Gi(o,t,r,i);case be.Scalar.QUOTE_DOUBLE:return Ir(o.value,t);case be.Scalar.QUOTE_SINGLE:return ao(o.value,t);case be.Scalar.PLAIN:return cm(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}fl.stringifyString=lm});var jr=w(so=>{"use strict";var um=Vi(),nt=P(),dm=Ar(),fm=Tr();function hm(e,t){let r=Object.assign({blockQuote:!0,commentString:dm.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function pm(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(nt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function mm(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(nt.isScalar(e)||nt.isCollection(e))&&e.anchor;a&&um.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function vm(e,t,r,i){if(nt.isPair(e))return e.toString(t,r,i);if(nt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=nt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=pm(t.doc.schema.tags,a));let o=mm(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):nt.isScalar(a)?fm.stringifyString(a,t,r,i):a.toString(t,r,i);return o?nt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}so.createStringifyContext=hm;so.stringify=vm});var vl=w(ml=>{"use strict";var We=P(),hl=H(),pl=jr(),$r=Ar();function gm({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=We.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(We.isCollection(e)||!We.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||We.isCollection(e)||(We.isScalar(e)?e.type===hl.Scalar.BLOCK_FOLDED||e.type===hl.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=pl.stringify(e,r,()=>v=!0,()=>h=!0);if(!p&&!r.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=$r.lineComment(m,r.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=$r.lineComment(m,r.indent,l(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=$r.lineComment(m,r.indent,l(f))));let y,b,S;We.isNode(t)?(y=!!t.spaceBefore,b=t.commentBefore,S=t.comment):(y=!1,b=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&We.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&We.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let E=!1,x=pl.stringify(t,r,()=>E=!0,()=>h=!0),g=" ";if(f||y||b){if(g=y?`
39
39
  `:"",b){let R=l(b);g+=`
40
40
  ${$r.indentComment(R,r.indent)}`}x===""&&!r.inFlow?g===`
41
41
  `&&S&&(g=`
42
42
 
43
43
  `):g+=`
44
- ${r.indent}`}else if(!p&&qe.isCollection(t)){let R=x[0],k=x.indexOf(`
44
+ ${r.indent}`}else if(!p&&We.isCollection(t)){let R=x[0],k=x.indexOf(`
45
45
  `),T=k!==-1,ie=r.inFlow??t.flow??t.items.length===0;if(T||!ie){let Ft=!1;if(T&&(R==="&"||R==="!")){let L=x.indexOf(" ");R==="&"&&L!==-1&&L<k&&x[L+1]==="!"&&(L=x.indexOf(" ",L+1)),(L===-1||k<L)&&(Ft=!0)}Ft||(g=`
46
46
  ${r.indent}`)}}else(x===""||x[0]===`
47
47
  `)&&(g="");return m+=g+x,r.inFlow?E&&i&&i():S&&!E?m+=$r.lineComment(m,r.indent,l(S)):h&&n&&n(),m}ml.stringifyPair=gm});var lo=w(co=>{"use strict";var gl=Oi("process");function wm(e,...t){e==="debug"&&console.log(...t)}function ym(e,t){(e==="debug"||e==="warn")&&(typeof gl.emitWarning=="function"?gl.emitWarning(t):console.warn(t))}co.debug=wm;co.warn=ym});var en=w(Zi=>{"use strict";var Qi=P(),wl=H(),Yi="<<",Xi={identify:e=>e===Yi||typeof e=="symbol"&&e.description===Yi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wl.Scalar(Symbol(Yi)),{addToJSMap:yl}),stringify:()=>Yi},Nm=(e,t)=>(Xi.identify(t)||Qi.isScalar(t)&&(!t.type||t.type===wl.Scalar.PLAIN)&&Xi.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Xi.tag&&r.default);function yl(e,t,r){let i=Nl(e,r);if(Qi.isSeq(i))for(let n of i.items)uo(e,t,n);else if(Array.isArray(i))for(let n of i)uo(e,t,n);else uo(e,t,i)}function uo(e,t,r){let i=Nl(e,r);if(!Qi.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Nl(e,t){return e&&Qi.isAlias(t)?t.resolve(e.doc,e):t}Zi.addMergeToJSMap=yl;Zi.isMergeKey=Nm;Zi.merge=Xi});var ho=w(Sl=>{"use strict";var bm=lo(),bl=en(),km=jr(),kl=P(),fo=tt();function Sm(e,t,{key:r,value:i}){if(kl.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(bl.isMergeKey(e,r))bl.addMergeToJSMap(e,t,i);else{let n=fo.toJS(r,"",e);if(t instanceof Map)t.set(n,fo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Em(r,n,e),o=fo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Em(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(kl.isNode(e)&&r?.doc){let i=km.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),bm.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Sl.addPairToJSMap=Sm});var at=w(po=>{"use strict";var El=Rr(),xm=vl(),Cm=ho(),tn=P();function Pm(e,t,r){let i=El.createNode(e,void 0,r),n=El.createNode(t,void 0,r);return new rn(i,n)}var rn=class e{constructor(t,r=null){Object.defineProperty(this,tn.NODE_TYPE,{value:tn.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return tn.isNode(r)&&(r=r.clone(t)),tn.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Cm.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?xm.stringifyPair(this,t,r,i):JSON.stringify(this)}};po.Pair=rn;po.createPair=Pm});var mo=w(Cl=>{"use strict";var Rt=P(),xl=jr(),nn=Ar();function Rm(e,t,r){return(t.inFlow??e.flow?_m:Am)(e,t,r)}function Am({comment:e,items:t},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 v=0;v<t.length;++v){let h=t[v],m=null;if(Rt.isNode(h))!d&&h.spaceBefore&&f.push(""),an(r,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(Rt.isPair(h)){let b=Rt.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&f.push(""),an(r,f,b.commentBefore,d))}d=!1;let y=xl.stringify(h,u,()=>m=null,()=>d=!0);m&&(y+=nn.lineComment(y,a,l(m))),d&&m&&(d=!1),f.push(i+y)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
@@ -116,24 +116,24 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
116
116
  `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function cd(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function hs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
117
  `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Pn.createScalarToken=Nw;Pn.resolveAsScalar=yw;Pn.setScalarValue=bw});var dd=w(ud=>{"use strict";var Sw=e=>"type"in e?An(e):Rn(e);function An(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=An(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Rn(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Rn(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Rn(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Rn({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=An(t)),r)for(let a of r)n+=a.source;return i&&(n+=An(i)),n}ud.stringify=Sw});var md=w(pd=>{"use strict";var ps=Symbol("break visit"),Ew=Symbol("skip children"),fd=Symbol("remove item");function Tt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),hd(Object.freeze([]),e,t)}Tt.BREAK=ps;Tt.SKIP=Ew;Tt.REMOVE=fd;Tt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Tt.parentCollection=(e,t)=>{let r=Tt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function hd(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=hd(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===ps)return ps;s===fd&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}pd.visit=Tt});var _n=w(Q=>{"use strict";var ms=ld(),xw=dd(),Cw=md(),vs="\uFEFF",gs="",ws="",ys="",Pw=e=>!!e&&"items"in e,Rw=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Aw(e){switch(e){case vs:return"<BOM>";case gs:return"<DOC>";case ws:return"<FLOW_END>";case ys:return"<SCALAR>";default:return JSON.stringify(e)}}function _w(e){switch(e){case vs:return"byte-order-mark";case gs:return"doc-mode";case ws:return"flow-error-end";case ys:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Q.createScalarToken=ms.createScalarToken;Q.resolveAsScalar=ms.resolveAsScalar;Q.setScalarValue=ms.setScalarValue;Q.stringify=xw.stringify;Q.visit=Cw.visit;Q.BOM=vs;Q.DOCUMENT=gs;Q.FLOW_END=ws;Q.SCALAR=ys;Q.isCollection=Pw;Q.isScalar=Rw;Q.prettyToken=Aw;Q.tokenType=_w});var ks=w(gd=>{"use strict";var Yr=_n();function be(e){switch(e){case void 0:case" ":case`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Q.createScalarToken=ms.createScalarToken;Q.resolveAsScalar=ms.resolveAsScalar;Q.setScalarValue=ms.setScalarValue;Q.stringify=xw.stringify;Q.visit=Cw.visit;Q.BOM=vs;Q.DOCUMENT=gs;Q.FLOW_END=ws;Q.SCALAR=ys;Q.isCollection=Pw;Q.isScalar=Rw;Q.prettyToken=Aw;Q.tokenType=_w});var ks=w(gd=>{"use strict";var Yr=_n();function ke(e){switch(e){case void 0:case" ":case`
120
120
  `:case"\r":case" ":return!0;default:return!1}}var vd=new Set("0123456789ABCDEFabcdef"),Iw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),In=new Set(",[]{}"),Tw=new Set(` ,[]{}
121
121
  \r `),Ns=e=>!e||Tw.has(e),bs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&be(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Yr.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Yr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&be(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&&!be(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&be(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ns),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&be(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Yr.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(Ns),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||be(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
125
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&ke(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Yr.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Yr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ke(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&&!ke(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ke(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ns),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&ke(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Yr.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(Ns),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ke(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>be(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
128
+ `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>ke(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
129
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
132
132
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Yr.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(be(a)||t&&In.has(a))break;r=i}else if(be(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Yr.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(ke(a)||t&&In.has(a))break;r=i}else if(ke(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
135
  `,a=this.buffer[i+1]):r=i),a==="#"||t&&In.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&In.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Yr.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Ns),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(be(i)||r&&In.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!be(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Iw.has(r))r=this.buffer[++t];else if(r==="%"&&vd.has(this.buffer[t+1])&&vd.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&In.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Yr.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Ns),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ke(i)||r&&In.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!ke(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Iw.has(r))r=this.buffer[++t];else if(r==="%"&&vd.has(this.buffer[t+1])&&vd.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
138
  `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};gd.Lexer=bs});var Es=w(wd=>{"use strict";var Ss=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};wd.LineCounter=Ss});var Cs=w(Sd=>{"use strict";var jw=Oi("process"),yd=_n(),$w=ks();function lt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Nd(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function kd(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Tn(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Zt(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function jn(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function bd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!lt(t.start,"explicit-key-ind")&&!lt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,kd(t.value)?t.value.end?jn(t.value.end,t.sep):t.value.end=t.sep:jn(t.start,t.sep),delete t.sep)}var xs=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new $w.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,jw.env.LOG_TOKENS&&console.log("|",yd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=yd.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&bd(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&&Nd(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Nd(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Tn(this.peek(2)),i=Zt(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
@@ -142,7 +142,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
142
142
  `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Tn(t),i=Zt(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=Tn(t),i=Zt(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Sd.Parser=xs});var Rd=w(Qr=>{"use strict";var Ed=fs(),Ow=qr(),Xr=Jr(),Hw=lo(),Dw=P(),Bw=Es(),xd=Cs();function Cd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Bw.LineCounter||null,prettyErrors:t}}function Lw(e,t={}){let{lineCounter:r,prettyErrors:i}=Cd(t),n=new xd.Parser(r?.addNewLine),a=new Ed.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Xr.prettifyError(e,r)),s.warnings.forEach(Xr.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Pd(e,t={}){let{lineCounter:r,prettyErrors:i}=Cd(t),n=new xd.Parser(r?.addNewLine),a=new Ed.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Xr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Xr.prettifyError(e,r)),o.warnings.forEach(Xr.prettifyError(e,r))),o}function Vw(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Pd(e,r);if(!n)return null;if(n.warnings.forEach(a=>Hw.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 Mw(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return Dw.isDocument(e)&&!i?e.toString(r):new Ow.Document(e,i,r).toString(r)}Qr.parse=Vw;Qr.parseAllDocuments=Lw;Qr.parseDocument=Pd;Qr.stringify=Mw});var er=w(A=>{"use strict";var Fw=fs(),qw=qr(),Ww=Jo(),Ps=Jr(),zw=Pr(),ut=P(),Jw=at(),Gw=H(),Uw=st(),Kw=ct(),Yw=_n(),Xw=ks(),Qw=Es(),Zw=Cs(),$n=Rd(),Ad=Sr();A.Composer=Fw.Composer;A.Document=qw.Document;A.Schema=Ww.Schema;A.YAMLError=Ps.YAMLError;A.YAMLParseError=Ps.YAMLParseError;A.YAMLWarning=Ps.YAMLWarning;A.Alias=zw.Alias;A.isAlias=ut.isAlias;A.isCollection=ut.isCollection;A.isDocument=ut.isDocument;A.isMap=ut.isMap;A.isNode=ut.isNode;A.isPair=ut.isPair;A.isScalar=ut.isScalar;A.isSeq=ut.isSeq;A.Pair=Jw.Pair;A.Scalar=Gw.Scalar;A.YAMLMap=Uw.YAMLMap;A.YAMLSeq=Kw.YAMLSeq;A.CST=Yw;A.Lexer=Xw.Lexer;A.LineCounter=Qw.LineCounter;A.Parser=Zw.Parser;A.parse=$n.parse;A.parseAllDocuments=$n.parseAllDocuments;A.parseDocument=$n.parseDocument;A.stringify=$n.stringify;A.visit=Ad.visit;A.visitAsync=Ad.visitAsync});import dt from"path";function $d(e,t){return tr[t][e]}function ny(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in tr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in tr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in tr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in tr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in tr.en)return s}return null}function ri(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,ei.stringify)(e).trimEnd().split(`
143
143
  `)){let s=ny(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of $d(s,t).split(`
144
144
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
145
- `)}function ay(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||dt.posix.isAbsolute(r)||dt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function jt(e){let t=ay(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Od(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Dn(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||dt.posix.isAbsolute(i)||dt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function We(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hd(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Bn(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>On)throw new Error(`${t} exceeds ${On} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Hn)throw new Error(`${t} contains more than ${Hn} wildcard tokens`);return e}function jd(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Bn(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Rs(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function oy(e){if(e===void 0)return{...ae,include:[...ae.include],exclude:[...ae.exclude]};let t=We(e,"native.snapshot");return{include:jd(t.include,"native.snapshot.include",ae.include),exclude:jd(t.exclude,"native.snapshot.exclude",ae.exclude),max_files:Rs(t.max_files,ae.max_files,"native.snapshot.max_files"),max_total_bytes:Rs(t.max_total_bytes,ae.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Rs(t.max_duration_ms,ae.max_duration_ms,"native.snapshot.max_duration_ms")}}function sy(e){if(e===void 0)return;let t=We(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=We(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:jt(i),toArtifactRoot:jt(n),stage:a,...o?{cleanup:o}:{}}}function cy(e){if(e===void 0)return;let t=We(e,"native.finish");if(t.pull_request===void 0)return{};let r=We(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(dt.posix.isAbsolute(i[0])||dt.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??ey;if(!Number.isSafeInteger(n)||n<1||n>Td)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Td}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function ly(e,t={}){let r=We(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??As;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=sy(r.pending_root_move),c=cy(r.finish);return{artifact_root:jt(i),language:Hd(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:oy(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function uy(e){let t=We(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Od(t.artifact_layout),language:Hd(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function dy(e){let r=We(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Dn(i,`hook.allow_paths[${n}]`)))]}}function fy(e){if(e===void 0)return{...Zr};let t=We(e,"memory"),r=t.learning??Zr.learning,i=t.retrieval??Zr.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 Is(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hy(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||dt.posix.isAbsolute(r)||dt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>_d)throw new Error(`${t} exceeds ${_d} 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>Id)throw new Error(`${t} contains more than ${Id} wildcard tokens`);return r}function py(e){let r=Is(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>hy(i,`knowledge.local.include[${n}]`)))]}}function my(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function vy(e){let t=Is(e,"knowledge.remote"),r=my(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function gy(e){if(e===void 0)return{..._s};let t=Is(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:py(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:vy(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function wy(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function yy(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.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(e.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:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function rr(e,t={}){let r=(0,ei.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=wy(n.ambient_resume),o=n.hook===void 0?void 0:dy(n.hook),s=fy(n.memory),c=gy(n.knowledge),l=n.native===void 0?void 0:ly(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:uy(n.classic),d=yy(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Dd(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Bd(e){let t=e.knowledge??{..._s};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Zr},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Dd(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function ne(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ii(e,t){let r=Bd(t),i=rr((0,ei.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...ne(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=ne(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=ne(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...ne(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...ne(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=ne(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=ne(a.finish);o.finish={...s,pull_request:{...ne(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...ne(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=ne(a.pending_root_move),c=Dd(i.native.pending_root_move),l=ne(s.cleanup),u=ne(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...ne(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Ln(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Zr},knowledge:{..._s},native:{artifact_root:jt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:As,snapshot:{...ae,include:[...ae.include],exclude:[...ae.exclude]}}}}var ei,ti,On,Hn,_d,Id,As,Zr,_s,ey,Td,ty,ry,iy,ae,tr,ft=N(()=>{"use strict";ei=kr(er(),1),ti=64*1024,On=1024,Hn=64,_d=1024,Id=64,As=5,Zr={learning:!0,retrieval:!0},_s={provider:"local"},ey=12e4,Td=6e5,ty=[".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/**"],ry=["**/.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"],iy=[...ty,...ry].sort((e,t)=>e.localeCompare(t,"en")),ae={include:["**/*"],exclude:[...iy],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},tr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
145
+ `)}function ay(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||dt.posix.isAbsolute(r)||dt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function jt(e){let t=ay(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Od(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Dn(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||dt.posix.isAbsolute(i)||dt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function ze(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hd(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Bn(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>On)throw new Error(`${t} exceeds ${On} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Hn)throw new Error(`${t} contains more than ${Hn} wildcard tokens`);return e}function jd(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Bn(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Rs(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function oy(e){if(e===void 0)return{...ae,include:[...ae.include],exclude:[...ae.exclude]};let t=ze(e,"native.snapshot");return{include:jd(t.include,"native.snapshot.include",ae.include),exclude:jd(t.exclude,"native.snapshot.exclude",ae.exclude),max_files:Rs(t.max_files,ae.max_files,"native.snapshot.max_files"),max_total_bytes:Rs(t.max_total_bytes,ae.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Rs(t.max_duration_ms,ae.max_duration_ms,"native.snapshot.max_duration_ms")}}function sy(e){if(e===void 0)return;let t=ze(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=ze(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:jt(i),toArtifactRoot:jt(n),stage:a,...o?{cleanup:o}:{}}}function cy(e){if(e===void 0)return;let t=ze(e,"native.finish");if(t.pull_request===void 0)return{};let r=ze(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(dt.posix.isAbsolute(i[0])||dt.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??ey;if(!Number.isSafeInteger(n)||n<1||n>Td)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Td}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function ly(e,t={}){let r=ze(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??As;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=sy(r.pending_root_move),c=cy(r.finish);return{artifact_root:jt(i),language:Hd(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:oy(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function uy(e){let t=ze(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Od(t.artifact_layout),language:Hd(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function dy(e){let r=ze(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Dn(i,`hook.allow_paths[${n}]`)))]}}function fy(e){if(e===void 0)return{...Zr};let t=ze(e,"memory"),r=t.learning??Zr.learning,i=t.retrieval??Zr.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 Is(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hy(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||dt.posix.isAbsolute(r)||dt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>_d)throw new Error(`${t} exceeds ${_d} 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>Id)throw new Error(`${t} contains more than ${Id} wildcard tokens`);return r}function py(e){let r=Is(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>hy(i,`knowledge.local.include[${n}]`)))]}}function my(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function vy(e){let t=Is(e,"knowledge.remote"),r=my(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function gy(e){if(e===void 0)return{..._s};let t=Is(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:py(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:vy(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function wy(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function yy(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.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(e.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:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function rr(e,t={}){let r=(0,ei.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=wy(n.ambient_resume),o=n.hook===void 0?void 0:dy(n.hook),s=fy(n.memory),c=gy(n.knowledge),l=n.native===void 0?void 0:ly(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:uy(n.classic),d=yy(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Dd(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Bd(e){let t=e.knowledge??{..._s};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Zr},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Dd(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function ne(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ii(e,t){let r=Bd(t),i=rr((0,ei.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...ne(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=ne(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=ne(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...ne(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...ne(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=ne(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=ne(a.finish);o.finish={...s,pull_request:{...ne(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...ne(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=ne(a.pending_root_move),c=Dd(i.native.pending_root_move),l=ne(s.cleanup),u=ne(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...ne(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Ln(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Zr},knowledge:{..._s},native:{artifact_root:jt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:As,snapshot:{...ae,include:[...ae.include],exclude:[...ae.exclude]}}}}var ei,ti,On,Hn,_d,Id,As,Zr,_s,ey,Td,ty,ry,iy,ae,tr,ft=N(()=>{"use strict";ei=kr(er(),1),ti=64*1024,On=1024,Hn=64,_d=1024,Id=64,As=5,Zr={learning:!0,retrieval:!0},_s={provider:"local"},ey=12e4,Td=6e5,ty=[".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/**"],ry=["**/.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"],iy=[...ty,...ry].sort((e,t)=>e.localeCompare(t,"en")),ae={include:["**/*"],exclude:[...iy],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},tr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
146
146
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
147
147
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
148
148
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -166,29 +166,29 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
166
166
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
167
167
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
168
168
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
169
- # 可选值:true | false`}}});function ht(e){return e!==0&&e!==0n&&e!=="0"}function je(e,t){return ht(e.dev)&&ht(t.dev)&&ht(e.ino)&&ht(t.ino)}function j(e,t){let r=ht(e.dev)&&ht(t.dev);if(r&&e.dev!==t.dev)return!1;let i=ht(e.ino)&&ht(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var ni=N(()=>{"use strict"});import{constants as Vn,promises as $t}from"fs";function Ts(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ld(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ai(e){return{dev:e.dev,ino:e.ino,birthtime:Ts(e)}}function Mn(e,t){let r=ai(e),i=ai(t);return je(r,i)?j(r,i):j(r,i)&&Ts(e)===Ts(t)&&Ld(e)===Ld(t)&&e.size===t.size}async function ir(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await $t.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ke("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ke("too-large",`${i} exceeds ${t} bytes`);let o=await $t.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ai(a)});let s=process.platform==="win32"?Vn.O_RDONLY:Vn.O_RDONLY|Vn.O_NOFOLLOW|Vn.O_NONBLOCK,c;try{c=await $t.open(e,s)}catch(l){throw l.code==="ELOOP"?new ke("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),$t.lstat(e,{bigint:n}),$t.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Mn(a,l)||!Mn(a,u))throw new ke("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ai(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-p,{bytesRead:S}=await c.read(v,0,Math.min(v.length,b),null);if(S===0)break;if(p+=S,p>t)throw new ke("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,m,y]=await Promise.all([c.stat({bigint:n}),$t.lstat(e,{bigint:n}),$t.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Mn(a,h)||!Mn(a,m))throw new ke("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:ai(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:y}}finally{await c.close()}}var ke,oi=N(()=>{"use strict";ni();ke=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Fn}from"fs";import pt from"path";function Ny(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function js(e,t){let r=pt.relative(e,t);return r===""||!pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pt.sep}`)}async function Vd(e,t){let r=pt.resolve(e),i=await Fn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Fn.realpath(r)}async function Md(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=pt.join(n,r[a]);let o;try{o=await Fn.lstat(n)}catch(u){if(Ny(u))return{exists:!1,kind:"missing"};throw u}let s=pt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Fn.realpath(n);if(!js(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function nr(e,t,r){let i=Dn(t,r.label),n=pt.resolve(e),a=await Vd(n,r.label),o=i.split("/"),s=pt.resolve(n,...o);if(!js(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Md(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function mt(e,t,r,i){let n=await nr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Vd(n.projectRoot,i.label);return ir(n.target,r,{...i,verify:async(o,s)=>{if(!js(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Md(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Ot=N(()=>{"use strict";oi();ft()});import{createHash as by}from"crypto";function $s(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function ky(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function qn(e,t={}){return(await ci(e,t)).document}async function Fd(e){try{return(await mt(e,si,ti,{label:si})).bytes}catch(t){if(ky(t))return null;throw t}}function qd(e){return e?{exists:!0,sha256:by("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Wn(e){return qd(await Fd(e))}async function ci(e,t={}){let r=await Fd(e);return{document:r?rr(r.toString("utf8"),t):null,identity:qd(r)}}async function Os(e){return(await qn(e))?.config??null}var si,ar=N(()=>{"use strict";ft();Ot();si=".comet/config.yaml"});var or=N(()=>{"use strict";ni()});var oC,Hs=N(()=>{"use strict";or();ar();Ot();oC=16*1024});async function Ds(e,t){if(!t)return;let r=await Wn(e);if(!$s(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Bs=N(()=>{"use strict";or();ft();ar();Ot();Hs()});var $e=N(()=>{"use strict";ni()});import{randomUUID as Cy}from"crypto";import{promises as M}from"fs";import Se from"path";function zn(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function Py(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Jn(e,t){return j({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Ry(e,t){return Jn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wd(e){let t=await M.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await M.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sr(e){for(let t of e){let r=await M.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Py(t,r)||await M.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Ay(e,t,r){let[i,n]=await Promise.all([M.lstat(e),M.realpath(e),r?sr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Jn(i,t)||r&&!zn(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function _y(e,t){let r=Se.resolve(e),i=Se.resolve(t);if(!zn(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Wd(r)],a=Se.relative(r,i).split(Se.sep).filter(Boolean),o=r;for(let s of a){await sr(n),o=Se.join(o,s);try{await M.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wd(o);if(!zn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await sr(n),n}async function Iy(e){let t;try{t=await M.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Ty(e,t,r={}){let i=Se.dirname(e),n=r.containedRoot?await _y(r.containedRoot,i):null;n||await M.mkdir(i,{recursive:!0});let a=Se.join(i,`.${Se.basename(e)}.${Cy()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await M.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([M.lstat(a),M.realpath(a)]);if(await sr(n),!l.isFile()||l.isSymbolicLink()||!Jn(s,l)||!zn(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Jn(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 Ay(a,c,n),await r.beforeCommit?.(),n){await sr(n);let l=await M.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Ry(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await M.link(a,e),await M.unlink(a)):await M.rename(a,e),await Iy(i)}catch(l){if(await o?.close(),!n)await M.rm(a,{force:!0});else try{await sr(n),await M.rm(a,{force:!0})}catch{}throw l}}async function ue(e,t,r={}){await Ty(e,t,r)}async function oe(e,t,r={}){await ue(e,JSON.stringify(t,null,2)+`
170
- `,r)}var D=N(()=>{"use strict";$e()});import{existsSync as zd,promises as ze}from"fs";import _ from"path";import jy from"os";async function Ls(e){try{return await ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Oy(e){try{let t=await ze.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lr(e,t){let r=_.relative(e,t);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function cr(e){let t=[],r=e;for(;!await Ls(r);){let n=_.dirname(r);if(n===r)break;t.push(_.basename(r)),r=n}let i=await ze.realpath(r);return _.resolve(i,...t.reverse())}async function Vs(e){try{return(await ze.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ms(e){let t=_.resolve(e);try{(await ze.stat(t)).isDirectory()||(t=_.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=_.resolve(jy.homedir());for(;;){if(!(t===i&&r!==i)){let o=_.join(t,...Gn.split("/")),s=t===r||await Oy(o);if(await Ls(o)&&s)return t}if(await Ls(_.join(t,".git")))return t;let a=_.dirname(t);if(a===t)return r;t=a}}function Fs(e){return jt(e)}async function Hy(e,t){let r=Fs(t),i=_.resolve(e,...r.split("/")),n=await ze.realpath(e),a=await cr(i);if(!lr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Je(e,t){let r=Fs(t),i=await Hy(e,r),n=_.join(i,"comet");if(await Vs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([cr(i),cr(n)]);if(!lr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(e),c=_.join(s,".comet","runtime","native");if(await Vs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([ze.realpath(s),cr(c)]);if(!lr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(e,...Gn.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:_.join(n,"specs"),changesDir:_.join(n,"changes"),archiveDir:_.join(n,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}async function Jd(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await I(e.nativeRoot,t),await ze.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await I(e.projectRoot,t),await ze.mkdir(t,{recursive:!0})}))}function Gd(e){if(!$y.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Gd(t);let r=_.join(e.changesRuntimeDir,t);if(!z(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Dy(e,t){Gd(t);let r=_.join(e.changesDir,t,"runtime");if(!z(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function de(e,t){let r=vt(e,t);if(zd(r))return r;let i=Dy(e,t);return zd(i)?i:r}function Ee(e,t){let r=_.resolve(t);if(z(e.runtimeDir,r))return e.runtimeDir;if(z(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function z(e,t){return lr(_.resolve(e),_.resolve(t))}async function I(e,t){let r=_.resolve(e),i=_.resolve(t);if(!lr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Vs(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([cr(r),cr(i)]);if(!lr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Gn,$y,$=N(()=>{"use strict";ft();Gn=".comet/config.yaml",$y=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import By from"path";function Ud(e="docs",t="en"){return Ln(e,t)}async function G(e){let t=(await qn(e))?.config??null;return t?.native?t:null}async function Kn(e){let t=await G(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function ui(e,t,r={}){let i=await ci(e,{allowPartialProject:!0}),n=ii(i.document?.value??{},t),a=By.join(e,...Gn.split("/"));await ue(a,ri(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Ds(e,i.identity)}})}var Un,fe=N(()=>{"use strict";ft();ar();Bs();D();$();Un=Bn});function qs(){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 ur,di,Kd,fi=N(()=>{"use strict";ur="comet.native.v4",di="comet.native.local-execution.v4",Kd=["multi-session","single-session"]});import{execFileSync as zy}from"child_process";import hi from"path";function wt(e,t){return zy("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Jy(e,t){let r=hi.normalize(e),i=hi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Z(e){try{let t=hi.resolve(wt(e,["rev-parse","--show-toplevel"])),i=wt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?hi.resolve(i.slice(9)):t,a=null;try{a=wt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Jy(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Yn(e){try{wt(e,["rev-parse","--is-inside-work-tree"]);let t=wt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:hi.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 dr(e){return Yn(e).map(t=>t.root)}function fr(e,t){try{return wt(e,["check-ref-format","--branch",t]),wt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function pi(e,t){try{let r=wt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var yt=N(()=>{"use strict"});function Yy(e,t){return zs[e][t]}function mi(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Yy(e,r)}
169
+ # 可选值:true | false`}}});function ht(e){return e!==0&&e!==0n&&e!=="0"}function $e(e,t){return ht(e.dev)&&ht(t.dev)&&ht(e.ino)&&ht(t.ino)}function j(e,t){let r=ht(e.dev)&&ht(t.dev);if(r&&e.dev!==t.dev)return!1;let i=ht(e.ino)&&ht(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var ni=N(()=>{"use strict"});import{constants as Vn,promises as $t}from"fs";function Ts(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ld(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ai(e){return{dev:e.dev,ino:e.ino,birthtime:Ts(e)}}function Mn(e,t){let r=ai(e),i=ai(t);return $e(r,i)?j(r,i):j(r,i)&&Ts(e)===Ts(t)&&Ld(e)===Ld(t)&&e.size===t.size}async function ir(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await $t.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Se("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Se("too-large",`${i} exceeds ${t} bytes`);let o=await $t.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ai(a)});let s=process.platform==="win32"?Vn.O_RDONLY:Vn.O_RDONLY|Vn.O_NOFOLLOW|Vn.O_NONBLOCK,c;try{c=await $t.open(e,s)}catch(l){throw l.code==="ELOOP"?new Se("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),$t.lstat(e,{bigint:n}),$t.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Mn(a,l)||!Mn(a,u))throw new Se("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ai(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-p,{bytesRead:S}=await c.read(v,0,Math.min(v.length,b),null);if(S===0)break;if(p+=S,p>t)throw new Se("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,m,y]=await Promise.all([c.stat({bigint:n}),$t.lstat(e,{bigint:n}),$t.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Mn(a,h)||!Mn(a,m))throw new Se("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:ai(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:y}}finally{await c.close()}}var Se,oi=N(()=>{"use strict";ni();Se=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Fn}from"fs";import pt from"path";function Ny(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function js(e,t){let r=pt.relative(e,t);return r===""||!pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pt.sep}`)}async function Vd(e,t){let r=pt.resolve(e),i=await Fn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Fn.realpath(r)}async function Md(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=pt.join(n,r[a]);let o;try{o=await Fn.lstat(n)}catch(u){if(Ny(u))return{exists:!1,kind:"missing"};throw u}let s=pt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Fn.realpath(n);if(!js(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function nr(e,t,r){let i=Dn(t,r.label),n=pt.resolve(e),a=await Vd(n,r.label),o=i.split("/"),s=pt.resolve(n,...o);if(!js(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Md(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function mt(e,t,r,i){let n=await nr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Vd(n.projectRoot,i.label);return ir(n.target,r,{...i,verify:async(o,s)=>{if(!js(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Md(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Ot=N(()=>{"use strict";oi();ft()});import{createHash as by}from"crypto";function $s(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function ky(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function qn(e,t={}){return(await ci(e,t)).document}async function Fd(e){try{return(await mt(e,si,ti,{label:si})).bytes}catch(t){if(ky(t))return null;throw t}}function qd(e){return e?{exists:!0,sha256:by("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Wn(e){return qd(await Fd(e))}async function ci(e,t={}){let r=await Fd(e);return{document:r?rr(r.toString("utf8"),t):null,identity:qd(r)}}async function Os(e){return(await qn(e))?.config??null}var si,ar=N(()=>{"use strict";ft();Ot();si=".comet/config.yaml"});var or=N(()=>{"use strict";ni()});var oC,Hs=N(()=>{"use strict";or();ar();Ot();oC=16*1024});async function Ds(e,t){if(!t)return;let r=await Wn(e);if(!$s(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Bs=N(()=>{"use strict";or();ft();ar();Ot();Hs()});var Oe=N(()=>{"use strict";ni()});import{randomUUID as Cy}from"crypto";import{promises as M}from"fs";import Ee from"path";function zn(e,t){let r=Ee.relative(e,t);return r===""||!Ee.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ee.sep}`)}function Py(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Jn(e,t){return j({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Ry(e,t){return Jn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wd(e){let t=await M.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await M.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function sr(e){for(let t of e){let r=await M.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Py(t,r)||await M.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Ay(e,t,r){let[i,n]=await Promise.all([M.lstat(e),M.realpath(e),r?sr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Jn(i,t)||r&&!zn(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function _y(e,t){let r=Ee.resolve(e),i=Ee.resolve(t);if(!zn(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Wd(r)],a=Ee.relative(r,i).split(Ee.sep).filter(Boolean),o=r;for(let s of a){await sr(n),o=Ee.join(o,s);try{await M.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wd(o);if(!zn(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await sr(n),n}async function Iy(e){let t;try{t=await M.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Ty(e,t,r={}){let i=Ee.dirname(e),n=r.containedRoot?await _y(r.containedRoot,i):null;n||await M.mkdir(i,{recursive:!0});let a=Ee.join(i,`.${Ee.basename(e)}.${Cy()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await M.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([M.lstat(a),M.realpath(a)]);if(await sr(n),!l.isFile()||l.isSymbolicLink()||!Jn(s,l)||!zn(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Jn(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 Ay(a,c,n),await r.beforeCommit?.(),n){await sr(n);let l=await M.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Ry(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await M.link(a,e),await M.unlink(a)):await M.rename(a,e),await Iy(i)}catch(l){if(await o?.close(),!n)await M.rm(a,{force:!0});else try{await sr(n),await M.rm(a,{force:!0})}catch{}throw l}}async function ue(e,t,r={}){await Ty(e,t,r)}async function oe(e,t,r={}){await ue(e,JSON.stringify(t,null,2)+`
170
+ `,r)}var D=N(()=>{"use strict";Oe()});import{existsSync as zd,promises as Je}from"fs";import _ from"path";import jy from"os";async function Ls(e){try{return await Je.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Oy(e){try{let t=await Je.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lr(e,t){let r=_.relative(e,t);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function cr(e){let t=[],r=e;for(;!await Ls(r);){let n=_.dirname(r);if(n===r)break;t.push(_.basename(r)),r=n}let i=await Je.realpath(r);return _.resolve(i,...t.reverse())}async function Vs(e){try{return(await Je.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ms(e){let t=_.resolve(e);try{(await Je.stat(t)).isDirectory()||(t=_.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=_.resolve(jy.homedir());for(;;){if(!(t===i&&r!==i)){let o=_.join(t,...Gn.split("/")),s=t===r||await Oy(o);if(await Ls(o)&&s)return t}if(await Ls(_.join(t,".git")))return t;let a=_.dirname(t);if(a===t)return r;t=a}}function Fs(e){return jt(e)}async function Hy(e,t){let r=Fs(t),i=_.resolve(e,...r.split("/")),n=await Je.realpath(e),a=await cr(i);if(!lr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ge(e,t){let r=Fs(t),i=await Hy(e,r),n=_.join(i,"comet");if(await Vs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([cr(i),cr(n)]);if(!lr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(e),c=_.join(s,".comet","runtime","native");if(await Vs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Je.realpath(s),cr(c)]);if(!lr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(e,...Gn.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:_.join(n,"specs"),changesDir:_.join(n,"changes"),archiveDir:_.join(n,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}async function Jd(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await I(e.nativeRoot,t),await Je.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await I(e.projectRoot,t),await Je.mkdir(t,{recursive:!0})}))}function Gd(e){if(!$y.test(e))throw new Error(`Invalid Native change name: ${e}`)}function vt(e,t){Gd(t);let r=_.join(e.changesRuntimeDir,t);if(!z(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Dy(e,t){Gd(t);let r=_.join(e.changesDir,t,"runtime");if(!z(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function de(e,t){let r=vt(e,t);if(zd(r))return r;let i=Dy(e,t);return zd(i)?i:r}function xe(e,t){let r=_.resolve(t);if(z(e.runtimeDir,r))return e.runtimeDir;if(z(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function z(e,t){return lr(_.resolve(e),_.resolve(t))}async function I(e,t){let r=_.resolve(e),i=_.resolve(t);if(!lr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Vs(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([cr(r),cr(i)]);if(!lr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Gn,$y,$=N(()=>{"use strict";ft();Gn=".comet/config.yaml",$y=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import By from"path";function Ud(e="docs",t="en"){return Ln(e,t)}async function G(e){let t=(await qn(e))?.config??null;return t?.native?t:null}async function Kn(e){let t=await G(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function ui(e,t,r={}){let i=await ci(e,{allowPartialProject:!0}),n=ii(i.document?.value??{},t),a=By.join(e,...Gn.split("/"));await ue(a,ri(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Ds(e,i.identity)}})}var Un,fe=N(()=>{"use strict";ft();ar();Bs();D();$();Un=Bn});function qs(){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 ur,di,Kd,fi=N(()=>{"use strict";ur="comet.native.v4",di="comet.native.local-execution.v4",Kd=["multi-session","single-session"]});import{execFileSync as zy}from"child_process";import hi from"path";function wt(e,t){return zy("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Jy(e,t){let r=hi.normalize(e),i=hi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Z(e){try{let t=hi.resolve(wt(e,["rev-parse","--show-toplevel"])),i=wt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?hi.resolve(i.slice(9)):t,a=null;try{a=wt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Jy(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Yn(e){try{wt(e,["rev-parse","--is-inside-work-tree"]);let t=wt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:hi.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 dr(e){return Yn(e).map(t=>t.root)}function fr(e,t){try{return wt(e,["check-ref-format","--branch",t]),wt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function pi(e,t){try{let r=wt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var yt=N(()=>{"use strict"});function Yy(e,t){return zs[e][t]}function mi(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Yy(e,r)}
171
171
  `).join(`
172
- `)}var zs,Gy,Uy,Ky,Zd,Dt=N(()=>{"use strict";zs={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:"验证预期"}},Gy={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:"结论"}},Uy={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:"结论"}},Ky=new Map,Zd=new Map;for(let e of Object.keys(zs)){for(let[t,r]of Object.entries(zs[e]))Ky.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Gy[e]))Zd.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Uy[e]))Zd.set(r.toLocaleLowerCase("en-US"),t)}});function Zy(e){return e.toLowerCase().startsWith(".env")}function vi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Zy(i))?"environment-file":r.some(i=>Qy.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Xy.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Xy,Qy,gi=N(()=>{"use strict";Xy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Qy=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as eN}from"node:crypto";import{promises as xe}from"node:fs";import he from"node:path";import{TextDecoder as tN}from"node:util";function Js(e,t){let r=he.relative(e,t);return r===""||!he.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${he.sep}`)}function rN(e){let t=he.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||he.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=vi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function iN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function nN(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return je(r,i)?j(r,i):j(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ef(e){let t=await xe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await xe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function aN(e,t){let r=he.resolve(e),i=he.resolve(t);if(!Js(r,i))throw new Error("Native artifact path is outside its root");let n=[await ef(r)],a=r;for(let o of he.relative(r,i).split(he.sep).filter(Boolean)){a=he.join(a,o);let s=await ef(a);if(!Js(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function tf(e){for(let t of e){let r=await xe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!nN(t,r)||await xe.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function pe(e){let t=rN(e.ref),r=e.maxBytes===null?null:iN(e.maxBytes??Qn),i=he.resolve(e.root,...t.split("/")),n=await aN(e.root,he.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await xe.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await xe.realpath(i);if(!Js(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await xe.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),xe.lstat(i),xe.realpath(i)]);if(await tf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Xn(a,c)||!Xn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let S=r===null?p.length:r+1-f,E=await s.read(p,0,Math.min(p.length,S),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),xe.lstat(i),xe.realpath(i)]);if(await tf(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Xn(c,v)||!Xn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let y=Buffer.concat(d,f),b;try{b=new tN("utf-8",{fatal:!0}).decode(y)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:eN("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}var Qn,Oe=N(()=>{"use strict";gi();$e();Qn=1024*1024});import{AsyncLocalStorage as oN}from"async_hooks";import{randomUUID as af}from"crypto";import{promises as me}from"fs";import of from"os";import F from"path";function cN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function lN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function cf(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function ea(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return je(r,i)?j(r,i):j(r,i)&&e.size===t.size}function Gs(e,t){return ea(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function He(e){let t,r;try{let i=await ir(e,rf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof ke?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${rf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:lN(JSON.parse(t.toString("utf8")),e),identity:cf(r)}}async function uN(e){return(await He(e))?.owner??null}function lf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==of.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dN(e,t){try{await me.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await me.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Us(e,t){let r=await He(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Gs(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await me.mkdir(t,{recursive:!0});let i=F.join(t,`${F.basename(e.file)}.${e.owner.id}.${af()}.removed`);try{await me.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await He(i);if(!n||n.owner.id!==e.owner.id||!ea(n.identity,e.identity))throw await dN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await me.rm(i,{force:!0}),"removed"}function uf(e){return{id:af(),pid:process.pid,hostname:of.hostname(),createdAt:new Date().toISOString(),operation:e}}async function df(e,t){let r;try{r=await me.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await uN(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
173
- `,"utf8"),await r.sync(),i=cf(await r.stat({bigint:!0}))}finally{await r.close()}let n=await He(e);if(!i||!n||n.owner.id!==t.id||!ea(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function fN(e,t){let r=await I(e.runtimeDir,e.locksDir);await me.mkdir(r,{recursive:!0});let i=await I(e.runtimeDir,F.join(r,sf));await me.mkdir(i,{recursive:!0});let n=uf(t),a=F.join(i,`.${n.id}.tmp`),o=F.join(i,`${n.id}.claim`);try{let s=await df(a,n);await me.rename(a,o);let c=await He(o);if(!c||!ea(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await me.rm(a,{force:!0})}}async function hN(e){let t=F.dirname(e.file),r=!1,i=F.basename(e.file);for(let n of await me.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=F.join(t,n.name);if(F.resolve(a)!==F.resolve(e.file))try{let o=await He(a),s=lf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Us(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function ff(e){let t=await He(e.file);if(t){if(t.owner.id!==e.owner.id||!Gs(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Us(t,F.dirname(e.file))}}async function pN(e,t){let r=Date.now()+sN;for(;;){let i=await fN(e,t);if(!await hN(i))return i;if(await ff(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function mN(e){let t=Zn.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Zn.set(e,n),await t,()=>{r(),Zn.get(e)===n&&Zn.delete(e)}}async function Ks(e,t,r){let i=F.resolve(e.locksDir),n=nf.getStore();if(n?.has(i))return r();let a=await mN(i);try{let o=await pN(e,t),s=new Map(n??[]);return s.set(i,o),await nf.run(s,async()=>{try{return await r()}finally{await ff(o)}})}finally{a()}}async function hf(e,t,r){let i=[...new Map(e.map(a=>[F.resolve(a.locksDir),a])).values()].sort((a,o)=>F.resolve(a.locksDir).localeCompare(F.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Ks(o,t,()=>n(a+1)):r()};return n(0)}async function ta(e,t,r){return Ks(e,`acquire ${t}`,async()=>{let i=await I(e.runtimeDir,e.locksDir);await me.mkdir(i,{recursive:!0});let n=await I(e.runtimeDir,F.join(i,cN(t))),a=uf(r),o=await df(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ra(e){await He(e.file)&&await Ks({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${F.basename(e.file)}`,async()=>{let t=await He(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Gs(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=F.join(e.locksDir,sf);await Us(t,r)})}function vN(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function pf(e){return lf(await He(e))}var rf,sf,sN,nf,Zn,wi=N(()=>{"use strict";oi();$();$e();rf=16*1024,sf=".coordinator",sN=5e3,nf=new oN,Zn=new Map});import{createHash as gN}from"crypto";function Ce(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function wN(e,t){t.has(e)&&Ce("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||Ce("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Ce("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ce("symbol properties are not supported"),`[${e.map(i=>Ys(i,t)).join(",")}]`}finally{t.delete(e)}}function yN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ce("only plain objects are supported"),t.has(e)&&Ce("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ce("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Ce("accessor properties are not supported"),`${JSON.stringify(o)}:${Ys(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ys(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Ce("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?wN(e,t):yN(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ce(`${typeof e} values are not supported`)}return Ce("unsupported value type")}function Xs(e){return Ys(e,new Set)}function ee(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return gN("sha256").update(`${e}
174
- ${Xs(t)}`).digest("hex")}var te=N(()=>{"use strict"});var lP,mf,ia=N(()=>{"use strict";Dt();te();lP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),mf=Object.freeze({maxCriteria:1024})});var Qs=N(()=>{"use strict";ia()});import{promises as SN}from"node:fs";function U(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function K(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function q(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Zs(e,t){return e===null?null:q(e,t)}function gf(e,t){let r=q(e,t);if(!PN.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function hr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function O(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function AN(e,t){return e===null?null:O(e,t,Number.MIN_SAFE_INTEGER)}function B(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function De(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function aa(e,t){return De(e,t,(r,i)=>q(r,`${t}[${i}]`))}function Bt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function pr(e,t){let r=q(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ec(e,t,r=!1){let i=q(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ve(e,t){let r=U(e,t);return K(r,new Set(["text","truncated"]),t),{text:q(r.text,`${t}.text`,{empty:!0}),truncated:hr(r.truncated,`${t}.truncated`)}}function _N(e,t){let r=`Native spec_changes[${t}]`,i=U(e,r);K(i,new Set(["capability","operation","source"]),r);let n=q(i.capability,`${r}.capability`);if(!xN.test(n))throw new Error(`${r}.capability is invalid`);let a=B(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ec(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 IN(e){let t="Native workspace",r=U(e,t);K(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=B(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Zs(r.change_branch,`${t}.change_branch`),a=Zs(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:B(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function TN(e){let t="Native loop",r=U(e,t);K(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=aa(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Bt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:B(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:B(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:O(r.goal_cycle,`${t}.goal_cycle`,1),iteration:O(r.iteration,`${t}.iteration`),attempt:O(r.attempt,`${t}.attempt`),retry_epoch:O(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:O(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:O(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:O(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Zs(r.next_action,`${t}.next_action`)}}function jN(e,t){let r=`Native acceptance[${t}]`,i=U(e,r);K(i,new Set(["id","source","text","result","reason"]),r);let n=q(i.id,`${r}.id`);if(!CN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ec(i.source,`${r}.source`),text:q(i.text,`${r}.text`),result:B(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ve(i.reason,`${r}.reason`)}}function $N(e,t){let r=`Native builder_handoff.checks[${t}]`,i=U(e,r);return K(i,new Set(["name","result","note"]),r),{name:ve(i.name,`${r}.name`),result:B(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ve(i.note,`${r}.note`)}}function ON(e){let t="Native builder_handoff",r=U(e,t);K(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=aa(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Bt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:U(r.review,`${t}.review`);return n&&K(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:q(r.candidate_id,`${t}.candidate_id`),identity_provider:q(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:q(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:O(r.iteration,`${t}.iteration`,1),summary:ve(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:De(r.checks,`${t}.checks`,$N),checks_truncated:hr(r.checks_truncated,`${t}.checks_truncated`),known_limits:De(r.known_limits,`${t}.known_limits`,(a,o)=>ve(a,`${t}.known_limits[${o}]`)),known_limits_truncated:hr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:B(n.status,["passed"],`${t}.review.status`),summary:ve(n.summary,`${t}.review.summary`),reviewer_execution_ref:q(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:pr(r.submitted_at,`${t}.submitted_at`)}}function HN(e,t){let r=`Native blockers[${t}]`,i=U(e,r);K(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=aa(i.acceptance_ids,`${r}.acceptance_ids`);return Bt(n,`${r}.acceptance_ids`),{owner:B(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:B(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function DN(e,t){let r=`Native verification.checks[${t}]`,i=U(e,r);return K(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:q(i.id,`${r}.id`),name:ve(i.name,`${r}.name`),argv_display:De(i.argv_display,`${r}.argv_display`,(n,a)=>ve(n,`${r}.argv_display[${a}]`)),argv_truncated:hr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ec(i.cwd_ref,`${r}.cwd_ref`,!0),status:B(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:AN(i.exit_code,`${r}.exit_code`),duration_ms:O(i.duration_ms,`${r}.duration_ms`)}}function BN(e){let t="Native verification",r=U(e,t);K(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=De(r.checks,`${t}.checks`,DN);Bt(i.map(a=>a.id),`${t}.checks IDs`);let n=q(r.identity_provider,`${t}.identity_provider`);return{candidate_id:q(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:q(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:O(r.iteration,`${t}.iteration`,1),attempt:O(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":B(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:B(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ve(r.summary,`${t}.summary`),risks:De(r.risks,`${t}.risks`,(a,o)=>ve(a,`${t}.risks[${o}]`)),risks_truncated:hr(r.risks_truncated,`${t}.risks_truncated`),completed_at:pr(r.completed_at,`${t}.completed_at`)}}function LN(e,t){let r=`Native history[${t}]`,i=U(e,r);K(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=aa(i.unresolved_ids,`${r}.unresolved_ids`);return Bt(n,`${r}.unresolved_ids`),{goal_cycle:O(i.goal_cycle,`${r}.goal_cycle`,1),iteration:O(i.iteration,`${r}.iteration`),attempt:O(i.attempt,`${r}.attempt`),outcome:B(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ve(i.summary,`${r}.summary`),completed_at:pr(i.completed_at,`${r}.completed_at`)}}function VN(e){let t="Native history_overflow.outcome_counts",r=U(e,t),i=["pass","fail","blocked","execution-error","recovery"];return K(r,new Set(i),t),{pass:O(r.pass,`${t}.pass`),fail:O(r.fail,`${t}.fail`),blocked:O(r.blocked,`${t}.blocked`),"execution-error":O(r["execution-error"],`${t}.execution-error`),recovery:O(r.recovery,`${t}.recovery`)}}function MN(e){let t="Native history_overflow",r=U(e,t);K(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=O(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:pr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:pr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=VN(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 FN(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function qN(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function mr(e){let t=U(e,"Native portable state");if(K(t,RN,"Native portable state"),t.schema!==ur)throw new Error(`Native portable state schema must be ${ur}`);let r=q(t.name,"Native state name");if(!EN.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=De(t.spec_changes,"Native spec_changes",_N);Bt(i.map(s=>s.capability),"Native spec change capabilities");let n=De(t.acceptance,"Native acceptance",jN);Bt(n.map(s=>s.id),"Native acceptance IDs");let a=De(t.history,"Native history",LN);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ur,name:r,language:B(t.language,["en","zh-CN"],"Native state language"),phase:B(t.phase,["shape","build","verify","archive"],"Native state phase"),status:B(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:O(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:gf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:gf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:B(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:IN(t.workspace),loop:TN(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ON(t.builder_handoff),blockers:De(t.blockers,"Native blockers",HN),verification:t.verification===null?null:BN(t.verification),history:a,history_overflow:MN(t.history_overflow),verification_result:B(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:B(t.verification_report,["verification.md"],"Native verification_report"),archived:hr(t.archived,"Native archived"),created_at:pr(t.created_at,"Native created_at")};return FN(o),qN(o),o}function wf(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return mr({schema:ur,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:qs(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function WN(e,t){let r=(0,na.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function tc(e){let t=await SN.readFile(e,"utf8");return mr(WN(t,"Native portable state"))}async function yf(e,t,r={}){let i=mr(t);await ue(e,(0,na.stringify)(i),r)}var na,EN,xN,CN,PN,RN,yi=N(()=>{"use strict";na=kr(er(),1);D();fi();EN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CN=/^A[1-9][0-9]*$/u,PN=/^[a-f0-9]{64}$/u,RN=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"])});var oa=N(()=>{"use strict"});var Ue,Ke,Ye,sa=N(()=>{"use strict";Ue="comet.native.v3",Ke="comet.native.v2",Ye="comet.native.v1"});function YN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function XN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function kf(e){let t=YN(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!zN.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Nf)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!GN.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!JN.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!KN.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!UN.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Nf,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:XN(t.createdAt,"Native portable migration transaction createdAt")}}var Nf,zN,JN,GN,UN,KN,Sf=N(()=>{"use strict";Y();Qs();yi();oa();fi();sa();Nf="comet.native.portable-migration.v1",zN=new Set(["schema","id","change","fromSchema","status","createdAt"]),JN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GN=/^[a-z0-9][a-z0-9-]{7,127}$/u,UN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),KN=new Set([Ye,Ke,Ue])});import QN from"node:path";function Pf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rf(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function ob(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Pf(e,r);if(Rf(i,ab,r),typeof i.capability!="string"||!Cf.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function sb(e){let t=Pf(e,"Native portable Archive transaction");if(Rf(t,nb,"Native portable Archive transaction"),t.schema!==Ef)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!tb.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Cf.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!rb.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!ib.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(ob);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Ef,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function rc(e){let t=ZN.exec(e);if(t)return{kind:"archive",change:t[1]};let r=eb.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Af(e,t){let r=rc(t);if(!r)return null;let i=await pe({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=QN.join(e.transactionsDir,t);if(r.kind==="archive"){let s=sb(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=kf(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function _f(e){return e.kind==="archive"||e.journal.status!=="committed"}var Ef,xf,ZN,eb,tb,rb,ib,nb,ab,Cf,ic=N(()=>{"use strict";Oe();Sf();Ef="comet.native.archive-transaction.v4",xf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",ZN=new RegExp(`^portable-archive-(${xf})\\.json$`,"u"),eb=new RegExp(`^portable-migration-(${xf})\\.json$`,"u"),tb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,rb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ib=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),nb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ab=new Set(["capability","operation","source","content"]),Cf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as cb}from"node:crypto";import{constants as da,promises as se}from"node:fs";import Pe from"node:path";import{TextDecoder as lb}from"node:util";function ha(e,t){let r=Pe.relative(e,t);return r===""||!Pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pe.sep}`)}function If(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ub(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function db(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function fa(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nc(e,t){let r=await se.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await se.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Tf(e,t,r){let i=Pe.resolve(e),n=Pe.resolve(t);if(!ha(i,n))throw new Error(`${r} is outside its managed root`);let a=[await nc(i,r)],o=i;for(let s of Pe.relative(i,n).split(Pe.sep).filter(Boolean)){await Xe(a,r),o=Pe.join(o,s);let c=await nc(o,r);if(!ha(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Xe(a,r),a}async function Xe(e,t){for(let r of e){let i=await se.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ub(r,i)||await se.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function fb(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Lt(e){let t=If(e.maxBytes),r=Pe.resolve(e.file),i=await Tf(e.root,Pe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>nc(Pe.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Xe(i,e.label);let a=await se.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=db(a),s=await se.realpath(r);if(!ha(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ha(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?da.O_RDONLY:da.O_RDONLY|da.O_NOFOLLOW|da.O_NONBLOCK,l=await se.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([se.lstat(r),se.realpath(r)]);if(await Xe(i,e.label),await Xe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!fa(o,u)||!fa(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await fb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),se.lstat(r),se.realpath(r)]);if(await Xe(i,e.label),await Xe(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!fa(o,v)||!fa(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:cb("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function jf(e){let t=await Lt(e),r;try{r=new lb("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Ni(e){let t=await Tf(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await se.readdir(e.directory,{withFileTypes:!0});else{let i=If(e.maxEntries);r=[];let n=await se.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Xe(t,e.label),{entries:r,verify:()=>Xe(t,e.label)}}var Be=N(()=>{"use strict";D();$e()});import Qe from"path";import{TextDecoder as pb}from"util";function ma(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function va(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Df(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ac(e,t){if(typeof e!="string"||e.length===0||Qe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function pa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $f(e,t){if(ac(e,t),e.includes("\\")||e!==Qe.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function bb(e,t){let r=ma(e,`transaction operations[${t}]`);if(va(r,vb,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ac(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ac(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Bf(e){let t=ma(e,"Native Archive transaction journal");if(va(t,gb,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Hf.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Df(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(pa(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=ma(s,`Archive transaction operations[${c}]`);if(va(l,wb,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);$f(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&$f(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&pa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(pa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);pa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function kb(e){let t=ma(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bf(t);if(va(t,mb,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Hf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Qe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Qe.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Df(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(bb),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function Sb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Qe.join(e.transactionsDir,t)}function Lf(e,t){let r=Sb(e,t);return{directory:r,journal:Qe.join(r,"transaction.json"),events:Qe.join(r,"events.jsonl"),staged:Qe.join(r,"staged"),backups:Qe.join(r,"backups")}}async function oc(e,t){let r=Lf(e,t);return await Promise.all(Object.values(r).map(i=>I(e.runtimeDir,i))),r}async function sc(e,t,r={}){let i=await oc(e,t),n=await Lt({root:e.runtimeDir,file:i.journal,maxBytes:yb,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(Nb.decode(n.bytes)),o=kb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var mb,vb,gb,wb,Hf,yb,GP,UP,KP,Nb,ga=N(()=>{"use strict";D();$();Be();mb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),vb=new Set(["id","type","source","target","staged","backup"]),gb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),wb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Hf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),yb=256*1024,GP=1024*1024,UP=16*1024,KP=64*1024*1024,Nb=new pb("utf-8",{fatal:!0})});import{promises as Eb}from"fs";import xb from"path";async function Cb(e,t,r){let i;try{i=await Eb.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await sc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(rc(n.name))try{let a=await Af(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(_f(a))return!0}catch{return!0}return!1}async function Pb(e,t){let r=Date.now()+5e3,i=xb.join(e.locksDir,"root-move.lock");for(;;)try{return await ta(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await pf(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function ge(e,t,r,i){let n=await Pb(e,t);try{if(await Kn(e.projectRoot),await Cb(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await ra(n)}}var Re=N(()=>{"use strict";fe();wi();ic();ga()});var Vf=N(()=>{"use strict"});import{createHash as Rb}from"crypto";function ce(e){return Rb("sha256").update(e).digest("hex")}var Le=N(()=>{"use strict"});import lc from"path";function wa(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Kb(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function Yb(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
172
+ `)}var zs,Gy,Uy,Ky,Zd,Dt=N(()=>{"use strict";zs={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:"验证预期"}},Gy={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:"结论"}},Uy={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:"结论"}},Ky=new Map,Zd=new Map;for(let e of Object.keys(zs)){for(let[t,r]of Object.entries(zs[e]))Ky.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Gy[e]))Zd.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Uy[e]))Zd.set(r.toLocaleLowerCase("en-US"),t)}});function Zy(e){return e.toLowerCase().startsWith(".env")}function vi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Zy(i))?"environment-file":r.some(i=>Qy.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Xy.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Xy,Qy,gi=N(()=>{"use strict";Xy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Qy=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as eN}from"node:crypto";import{promises as Ce}from"node:fs";import pe from"node:path";import{TextDecoder as tN}from"node:util";function Js(e,t){let r=pe.relative(e,t);return r===""||!pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pe.sep}`)}function rN(e){let t=pe.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||pe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=vi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function iN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function nN(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Xn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return $e(r,i)?j(r,i):j(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function ef(e){let t=await Ce.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ce.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function aN(e,t){let r=pe.resolve(e),i=pe.resolve(t);if(!Js(r,i))throw new Error("Native artifact path is outside its root");let n=[await ef(r)],a=r;for(let o of pe.relative(r,i).split(pe.sep).filter(Boolean)){a=pe.join(a,o);let s=await ef(a);if(!Js(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function tf(e){for(let t of e){let r=await Ce.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!nN(t,r)||await Ce.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function me(e){let t=rN(e.ref),r=e.maxBytes===null?null:iN(e.maxBytes??Qn),i=pe.resolve(e.root,...t.split("/")),n=await aN(e.root,pe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Ce.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Ce.realpath(i);if(!Js(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ce.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),Ce.lstat(i),Ce.realpath(i)]);if(await tf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Xn(a,c)||!Xn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let S=r===null?p.length:r+1-f,E=await s.read(p,0,Math.min(p.length,S),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ce.lstat(i),Ce.realpath(i)]);if(await tf(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Xn(c,v)||!Xn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let y=Buffer.concat(d,f),b;try{b=new tN("utf-8",{fatal:!0}).decode(y)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:eN("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}var Qn,He=N(()=>{"use strict";gi();Oe();Qn=1024*1024});import{AsyncLocalStorage as oN}from"async_hooks";import{randomUUID as af}from"crypto";import{promises as ve}from"fs";import of from"os";import F from"path";function cN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function lN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function cf(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function ea(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return $e(r,i)?j(r,i):j(r,i)&&e.size===t.size}function Gs(e,t){return ea(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function De(e){let t,r;try{let i=await ir(e,rf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Se?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${rf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:lN(JSON.parse(t.toString("utf8")),e),identity:cf(r)}}async function uN(e){return(await De(e))?.owner??null}function lf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==of.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=vN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function dN(e,t){try{await ve.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ve.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Us(e,t){let r=await De(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Gs(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ve.mkdir(t,{recursive:!0});let i=F.join(t,`${F.basename(e.file)}.${e.owner.id}.${af()}.removed`);try{await ve.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await De(i);if(!n||n.owner.id!==e.owner.id||!ea(n.identity,e.identity))throw await dN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ve.rm(i,{force:!0}),"removed"}function uf(e){return{id:af(),pid:process.pid,hostname:of.hostname(),createdAt:new Date().toISOString(),operation:e}}async function df(e,t){let r;try{r=await ve.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await uN(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
173
+ `,"utf8"),await r.sync(),i=cf(await r.stat({bigint:!0}))}finally{await r.close()}let n=await De(e);if(!i||!n||n.owner.id!==t.id||!ea(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function fN(e,t){let r=await I(e.runtimeDir,e.locksDir);await ve.mkdir(r,{recursive:!0});let i=await I(e.runtimeDir,F.join(r,sf));await ve.mkdir(i,{recursive:!0});let n=uf(t),a=F.join(i,`.${n.id}.tmp`),o=F.join(i,`${n.id}.claim`);try{let s=await df(a,n);await ve.rename(a,o);let c=await De(o);if(!c||!ea(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await ve.rm(a,{force:!0})}}async function hN(e){let t=F.dirname(e.file),r=!1,i=F.basename(e.file);for(let n of await ve.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=F.join(t,n.name);if(F.resolve(a)!==F.resolve(e.file))try{let o=await De(a),s=lf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Us(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function ff(e){let t=await De(e.file);if(t){if(t.owner.id!==e.owner.id||!Gs(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Us(t,F.dirname(e.file))}}async function pN(e,t){let r=Date.now()+sN;for(;;){let i=await fN(e,t);if(!await hN(i))return i;if(await ff(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function mN(e){let t=Zn.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Zn.set(e,n),await t,()=>{r(),Zn.get(e)===n&&Zn.delete(e)}}async function Ks(e,t,r){let i=F.resolve(e.locksDir),n=nf.getStore();if(n?.has(i))return r();let a=await mN(i);try{let o=await pN(e,t),s=new Map(n??[]);return s.set(i,o),await nf.run(s,async()=>{try{return await r()}finally{await ff(o)}})}finally{a()}}async function hf(e,t,r){let i=[...new Map(e.map(a=>[F.resolve(a.locksDir),a])).values()].sort((a,o)=>F.resolve(a.locksDir).localeCompare(F.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Ks(o,t,()=>n(a+1)):r()};return n(0)}async function ta(e,t,r){return Ks(e,`acquire ${t}`,async()=>{let i=await I(e.runtimeDir,e.locksDir);await ve.mkdir(i,{recursive:!0});let n=await I(e.runtimeDir,F.join(i,cN(t))),a=uf(r),o=await df(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ra(e){await De(e.file)&&await Ks({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${F.basename(e.file)}`,async()=>{let t=await De(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Gs(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=F.join(e.locksDir,sf);await Us(t,r)})}function vN(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function pf(e){return lf(await De(e))}var rf,sf,sN,nf,Zn,wi=N(()=>{"use strict";oi();$();Oe();rf=16*1024,sf=".coordinator",sN=5e3,nf=new oN,Zn=new Map});import{createHash as gN}from"crypto";function Pe(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function wN(e,t){t.has(e)&&Pe("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||Pe("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Pe("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Pe("symbol properties are not supported"),`[${e.map(i=>Ys(i,t)).join(",")}]`}finally{t.delete(e)}}function yN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Pe("only plain objects are supported"),t.has(e)&&Pe("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Pe("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Pe("accessor properties are not supported"),`${JSON.stringify(o)}:${Ys(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ys(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Pe("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?wN(e,t):yN(e,t);case"bigint":case"function":case"symbol":case"undefined":return Pe(`${typeof e} values are not supported`)}return Pe("unsupported value type")}function Xs(e){return Ys(e,new Set)}function ee(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return gN("sha256").update(`${e}
174
+ ${Xs(t)}`).digest("hex")}var te=N(()=>{"use strict"});var lP,mf,ia=N(()=>{"use strict";Dt();te();lP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),mf=Object.freeze({maxCriteria:1024})});var Qs=N(()=>{"use strict";ia()});import{promises as SN}from"node:fs";function U(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function K(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function q(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Zs(e,t){return e===null?null:q(e,t)}function gf(e,t){let r=q(e,t);if(!PN.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function hr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function O(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function AN(e,t){return e===null?null:O(e,t,Number.MIN_SAFE_INTEGER)}function B(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Be(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function aa(e,t){return Be(e,t,(r,i)=>q(r,`${t}[${i}]`))}function Bt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function pr(e,t){let r=q(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ec(e,t,r=!1){let i=q(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ge(e,t){let r=U(e,t);return K(r,new Set(["text","truncated"]),t),{text:q(r.text,`${t}.text`,{empty:!0}),truncated:hr(r.truncated,`${t}.truncated`)}}function _N(e,t){let r=`Native spec_changes[${t}]`,i=U(e,r);K(i,new Set(["capability","operation","source"]),r);let n=q(i.capability,`${r}.capability`);if(!xN.test(n))throw new Error(`${r}.capability is invalid`);let a=B(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ec(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 IN(e){let t="Native workspace",r=U(e,t);K(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=B(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Zs(r.change_branch,`${t}.change_branch`),a=Zs(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:B(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function TN(e){let t="Native loop",r=U(e,t);K(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=aa(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Bt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:B(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:B(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:O(r.goal_cycle,`${t}.goal_cycle`,1),iteration:O(r.iteration,`${t}.iteration`),attempt:O(r.attempt,`${t}.attempt`),retry_epoch:O(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:O(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:O(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:O(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Zs(r.next_action,`${t}.next_action`)}}function jN(e,t){let r=`Native acceptance[${t}]`,i=U(e,r);K(i,new Set(["id","source","text","result","reason"]),r);let n=q(i.id,`${r}.id`);if(!CN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ec(i.source,`${r}.source`),text:q(i.text,`${r}.text`),result:B(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ge(i.reason,`${r}.reason`)}}function $N(e,t){let r=`Native builder_handoff.checks[${t}]`,i=U(e,r);return K(i,new Set(["name","result","note"]),r),{name:ge(i.name,`${r}.name`),result:B(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ge(i.note,`${r}.note`)}}function ON(e){let t="Native builder_handoff",r=U(e,t);K(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=aa(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Bt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:U(r.review,`${t}.review`);return n&&K(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:q(r.candidate_id,`${t}.candidate_id`),identity_provider:q(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:q(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:O(r.iteration,`${t}.iteration`,1),summary:ge(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Be(r.checks,`${t}.checks`,$N),checks_truncated:hr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Be(r.known_limits,`${t}.known_limits`,(a,o)=>ge(a,`${t}.known_limits[${o}]`)),known_limits_truncated:hr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:B(n.status,["passed"],`${t}.review.status`),summary:ge(n.summary,`${t}.review.summary`),reviewer_execution_ref:q(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:pr(r.submitted_at,`${t}.submitted_at`)}}function HN(e,t){let r=`Native blockers[${t}]`,i=U(e,r);K(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=aa(i.acceptance_ids,`${r}.acceptance_ids`);return Bt(n,`${r}.acceptance_ids`),{owner:B(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ge(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:B(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function DN(e,t){let r=`Native verification.checks[${t}]`,i=U(e,r);return K(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:q(i.id,`${r}.id`),name:ge(i.name,`${r}.name`),argv_display:Be(i.argv_display,`${r}.argv_display`,(n,a)=>ge(n,`${r}.argv_display[${a}]`)),argv_truncated:hr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ec(i.cwd_ref,`${r}.cwd_ref`,!0),status:B(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:AN(i.exit_code,`${r}.exit_code`),duration_ms:O(i.duration_ms,`${r}.duration_ms`)}}function BN(e){let t="Native verification",r=U(e,t);K(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Be(r.checks,`${t}.checks`,DN);Bt(i.map(a=>a.id),`${t}.checks IDs`);let n=q(r.identity_provider,`${t}.identity_provider`);return{candidate_id:q(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:q(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:O(r.iteration,`${t}.iteration`,1),attempt:O(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":B(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:B(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ge(r.summary,`${t}.summary`),risks:Be(r.risks,`${t}.risks`,(a,o)=>ge(a,`${t}.risks[${o}]`)),risks_truncated:hr(r.risks_truncated,`${t}.risks_truncated`),completed_at:pr(r.completed_at,`${t}.completed_at`)}}function LN(e,t){let r=`Native history[${t}]`,i=U(e,r);K(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=aa(i.unresolved_ids,`${r}.unresolved_ids`);return Bt(n,`${r}.unresolved_ids`),{goal_cycle:O(i.goal_cycle,`${r}.goal_cycle`,1),iteration:O(i.iteration,`${r}.iteration`),attempt:O(i.attempt,`${r}.attempt`),outcome:B(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ge(i.summary,`${r}.summary`),completed_at:pr(i.completed_at,`${r}.completed_at`)}}function VN(e){let t="Native history_overflow.outcome_counts",r=U(e,t),i=["pass","fail","blocked","execution-error","recovery"];return K(r,new Set(i),t),{pass:O(r.pass,`${t}.pass`),fail:O(r.fail,`${t}.fail`),blocked:O(r.blocked,`${t}.blocked`),"execution-error":O(r["execution-error"],`${t}.execution-error`),recovery:O(r.recovery,`${t}.recovery`)}}function MN(e){let t="Native history_overflow",r=U(e,t);K(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=O(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:pr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:pr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=VN(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 FN(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function qN(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function mr(e){let t=U(e,"Native portable state");if(K(t,RN,"Native portable state"),t.schema!==ur)throw new Error(`Native portable state schema must be ${ur}`);let r=q(t.name,"Native state name");if(!EN.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Be(t.spec_changes,"Native spec_changes",_N);Bt(i.map(s=>s.capability),"Native spec change capabilities");let n=Be(t.acceptance,"Native acceptance",jN);Bt(n.map(s=>s.id),"Native acceptance IDs");let a=Be(t.history,"Native history",LN);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ur,name:r,language:B(t.language,["en","zh-CN"],"Native state language"),phase:B(t.phase,["shape","build","verify","archive"],"Native state phase"),status:B(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:O(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:gf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:gf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:B(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:IN(t.workspace),loop:TN(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ON(t.builder_handoff),blockers:Be(t.blockers,"Native blockers",HN),verification:t.verification===null?null:BN(t.verification),history:a,history_overflow:MN(t.history_overflow),verification_result:B(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:B(t.verification_report,["verification.md"],"Native verification_report"),archived:hr(t.archived,"Native archived"),created_at:pr(t.created_at,"Native created_at")};return FN(o),qN(o),o}function wf(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return mr({schema:ur,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:qs(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function WN(e,t){let r=(0,na.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function tc(e){let t=await SN.readFile(e,"utf8");return mr(WN(t,"Native portable state"))}async function yf(e,t,r={}){let i=mr(t);await ue(e,(0,na.stringify)(i),r)}var na,EN,xN,CN,PN,RN,yi=N(()=>{"use strict";na=kr(er(),1);D();fi();EN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CN=/^A[1-9][0-9]*$/u,PN=/^[a-f0-9]{64}$/u,RN=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"])});var oa=N(()=>{"use strict"});var Ue,Ke,Ye,sa=N(()=>{"use strict";Ue="comet.native.v3",Ke="comet.native.v2",Ye="comet.native.v1"});function YN(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function XN(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function kf(e){let t=YN(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!zN.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Nf)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!GN.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!JN.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!KN.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!UN.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Nf,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:XN(t.createdAt,"Native portable migration transaction createdAt")}}var Nf,zN,JN,GN,UN,KN,Sf=N(()=>{"use strict";Y();Qs();yi();oa();fi();sa();Nf="comet.native.portable-migration.v1",zN=new Set(["schema","id","change","fromSchema","status","createdAt"]),JN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GN=/^[a-z0-9][a-z0-9-]{7,127}$/u,UN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),KN=new Set([Ye,Ke,Ue])});import QN from"node:path";function Pf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rf(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function ob(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Pf(e,r);if(Rf(i,ab,r),typeof i.capability!="string"||!Cf.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function sb(e){let t=Pf(e,"Native portable Archive transaction");if(Rf(t,nb,"Native portable Archive transaction"),t.schema!==Ef)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!tb.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Cf.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!rb.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!ib.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(ob);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Ef,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function rc(e){let t=ZN.exec(e);if(t)return{kind:"archive",change:t[1]};let r=eb.exec(e);return r?{kind:"migration",change:r[1]}:null}async function Af(e,t){let r=rc(t);if(!r)return null;let i=await me({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=QN.join(e.transactionsDir,t);if(r.kind==="archive"){let s=sb(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=kf(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}function _f(e){return e.kind==="archive"||e.journal.status!=="committed"}var Ef,xf,ZN,eb,tb,rb,ib,nb,ab,Cf,ic=N(()=>{"use strict";He();Sf();Ef="comet.native.archive-transaction.v4",xf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",ZN=new RegExp(`^portable-archive-(${xf})\\.json$`,"u"),eb=new RegExp(`^portable-migration-(${xf})\\.json$`,"u"),tb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,rb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ib=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),nb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ab=new Set(["capability","operation","source","content"]),Cf=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as cb}from"node:crypto";import{constants as da,promises as se}from"node:fs";import Re from"node:path";import{TextDecoder as lb}from"node:util";function ha(e,t){let r=Re.relative(e,t);return r===""||!Re.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Re.sep}`)}function If(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ub(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function db(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function fa(e,t){return j({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nc(e,t){let r=await se.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await se.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Tf(e,t,r){let i=Re.resolve(e),n=Re.resolve(t);if(!ha(i,n))throw new Error(`${r} is outside its managed root`);let a=[await nc(i,r)],o=i;for(let s of Re.relative(i,n).split(Re.sep).filter(Boolean)){await Xe(a,r),o=Re.join(o,s);let c=await nc(o,r);if(!ha(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Xe(a,r),a}async function Xe(e,t){for(let r of e){let i=await se.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ub(r,i)||await se.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function fb(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Lt(e){let t=If(e.maxBytes),r=Re.resolve(e.file),i=await Tf(e.root,Re.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>nc(Re.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Xe(i,e.label);let a=await se.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=db(a),s=await se.realpath(r);if(!ha(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ha(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?da.O_RDONLY:da.O_RDONLY|da.O_NOFOLLOW|da.O_NONBLOCK,l=await se.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([se.lstat(r),se.realpath(r)]);if(await Xe(i,e.label),await Xe(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!fa(o,u)||!fa(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await fb(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),se.lstat(r),se.realpath(r)]);if(await Xe(i,e.label),await Xe(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!fa(o,v)||!fa(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:cb("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function jf(e){let t=await Lt(e),r;try{r=new lb("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function Ni(e){let t=await Tf(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await se.readdir(e.directory,{withFileTypes:!0});else{let i=If(e.maxEntries);r=[];let n=await se.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Xe(t,e.label),{entries:r,verify:()=>Xe(t,e.label)}}var Le=N(()=>{"use strict";D();Oe()});import Qe from"path";import{TextDecoder as pb}from"util";function ma(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function va(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Df(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ac(e,t){if(typeof e!="string"||e.length===0||Qe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function pa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $f(e,t){if(ac(e,t),e.includes("\\")||e!==Qe.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function bb(e,t){let r=ma(e,`transaction operations[${t}]`);if(va(r,vb,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ac(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ac(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Bf(e){let t=ma(e,"Native Archive transaction journal");if(va(t,gb,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Hf.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Df(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(pa(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=ma(s,`Archive transaction operations[${c}]`);if(va(l,wb,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);$f(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&$f(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&pa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(pa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);pa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function kb(e){let t=ma(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bf(t);if(va(t,mb,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Hf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Qe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Qe.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Df(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(bb),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function Sb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Qe.join(e.transactionsDir,t)}function Lf(e,t){let r=Sb(e,t);return{directory:r,journal:Qe.join(r,"transaction.json"),events:Qe.join(r,"events.jsonl"),staged:Qe.join(r,"staged"),backups:Qe.join(r,"backups")}}async function oc(e,t){let r=Lf(e,t);return await Promise.all(Object.values(r).map(i=>I(e.runtimeDir,i))),r}async function sc(e,t,r={}){let i=await oc(e,t),n=await Lt({root:e.runtimeDir,file:i.journal,maxBytes:yb,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(Nb.decode(n.bytes)),o=kb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var mb,vb,gb,wb,Hf,yb,GP,UP,KP,Nb,ga=N(()=>{"use strict";D();$();Le();mb=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),vb=new Set(["id","type","source","target","staged","backup"]),gb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),wb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Hf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),yb=256*1024,GP=1024*1024,UP=16*1024,KP=64*1024*1024,Nb=new pb("utf-8",{fatal:!0})});import{promises as Eb}from"fs";import xb from"path";async function Cb(e,t,r){let i;try{i=await Eb.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await sc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(rc(n.name))try{let a=await Af(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(_f(a))return!0}catch{return!0}return!1}async function Pb(e,t){let r=Date.now()+5e3,i=xb.join(e.locksDir,"root-move.lock");for(;;)try{return await ta(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await pf(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function we(e,t,r,i){let n=await Pb(e,t);try{if(await Kn(e.projectRoot),await Cb(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await ra(n)}}var Ae=N(()=>{"use strict";fe();wi();ic();ga()});var Vf=N(()=>{"use strict"});import{createHash as Rb}from"crypto";function ce(e){return Rb("sha256").update(e).digest("hex")}var Ve=N(()=>{"use strict"});import lc from"path";function wa(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Kb(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function Yb(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
175
175
  `)}function Xb(e,t){return ce(`comet.native.snapshot-policy.v1
176
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function cc(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function Qb(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Mf(e){let t=Un(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?Qb(n):void 0;if(a&&!a())return!1;let o=cc(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=cc(r,c,a),o===null||o.size===0)return!1}return cc(r,o,a)?.has(r.length)??!1}}function Zb(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Un(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Un(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=Xb(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(Mf),excludeMatchers:r.map(Mf),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 we(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ye(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function gr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ve(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Wf(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=lc.posix.normalize(e);if(r!==e||lc.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function ek(e,t){let r=we(e,`Native snapshot entry ${t}`);ye(r,Fb,`Native snapshot entry ${t}`);let i=Wf(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!ya.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Ve(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Ub.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function tk(e,t){let r=we(e,`Native snapshot omission ${t}`);if(ye(r,qb,`Native snapshot omission ${t}`),!Jb.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!Gb.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Wf(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Ve(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function rk(e){let t=we(e,"Native snapshot omission overflow");if(ye(t,Wb,"Native snapshot omission overflow"),typeof t.hash!="string"||!ya.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:gr(t.count,"Native snapshot omission overflow count")}}function vr(e,t){let r=we(e,t);if(ye(r,Lb,t),typeof r.hash!="string"||!ya.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Ve(r.recordCount,`${t} recordCount`),n=Ve(r.storedRecordCount,`${t} storedRecordCount`),a=Ve(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Ff(e){let t=we(e,"Native Git selection evidence");if(ye(t,Bb,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=vr(t.stageBefore,"Native Git selection stageBefore"),i=vr(t.combined,"Native Git selection combined"),n=vr(t.stageAfter,"Native Git selection stageAfter"),a=vr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=vr(t.finalCombined,"Native Git selection finalCombined"),s=vr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!wa(r,n)||!wa(n,a)||!wa(i,o)||!wa(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(t.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 qf(e,t){let r=we(e,t);if(ye(r,Mb,t),typeof r.hash!="string"||!ya.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Ve(r.visitedNodeCount,`${t} visitedNodeCount`),n=Ve(r.recordCount,`${t} recordCount`),a=Ve(r.storedRecordCount,`${t} storedRecordCount`),o=Ve(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function ik(e){let t=we(e,"Native physical selection evidence");if(ye(t,Vb,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=qf(t.before,"Native physical selection before"),i=qf(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Kb(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function zf(e){let t=we(e,"Native content snapshot manifest");if(ye(t,jb,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zb.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let g=we(t.capture,"Native content snapshot capture");if(ye(g,Hb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=g.gitSelection===void 0?void 0:Ff(g.gitSelection),k=g.physicalSelection===void 0?void 0:ik(g.physicalSelection),T=null;if(g.projection!==void 0){let ie=we(g.projection,"Native content snapshot projection");if(ye(ie,Db,"Native content snapshot projection"),ie.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");T={provider:"git",...ie.selection===void 0?{}:{selection:Ff(ie.selection)}}}if(g.provider==="git"){if(k||T)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&T)throw new Error("Native physical-tree capture cannot combine selection and projection");r=T?{provider:"physical-tree",projection:T}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=we(t.limits,"Native content snapshot limits");ye(i,$b,"Native content snapshot limits");let n={maxFiles:gr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:gr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:gr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:gr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:gr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=we(t.policy,"Native snapshot policy");if(ye(g,Ob,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Zb({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(ek),s=t.omitted.map(tk),c=Ve(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:rk(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>n.maxFileBytes)||o.reduce((g,R)=>g+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>_b||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(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.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 p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",E=b?.status==="changed"||b?.status==="overflow-and-changed";if(S!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let x={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Yb(x)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return x}function nk(e,t){if(!Tb.test(t))throw new Error(`Invalid Native change name: ${t}`);return lc.join(de(e,t),"baseline-manifest.json")}async function Jf(e,t){let r=nk(e,t),i=Ee(e,r);await I(i,r);try{let n=await jf({root:i,file:r,maxBytes:Ib,label:"Native baseline snapshot manifest"});return zf(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var mR,_b,Ib,Tb,jb,$b,Ob,Hb,Db,Bb,Lb,Vb,Mb,Fb,qb,Wb,zb,Jb,Gb,ya,Ub,vR,gR,wR,yR,NR,bi=N(()=>{"use strict";D();fe();Le();$e();$();Be();gi();mR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},_b=1e3,Ib=8*1024*1024,Tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$b=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Ob=new Set(["schema","include","exclude","hash"]),Hb=new Set(["provider","gitSelection","physicalSelection","projection"]),Db=new Set(["provider","selection"]),Bb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Lb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Vb=new Set(["schema","status","before","after"]),Mb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Fb=new Set(["path","hash","size","type","gitObjectId"]),qb=new Set(["path","size","type","reason"]),Wb=new Set(["ref","hash","count"]),zb=new Set(["change-created","legacy-migration","explicit"]),Jb=new Set(["file","directory","other"]),Gb=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"]),ya=/^[a-f0-9]{64}$/u,Ub=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,vR=64*1024,gR=64*1024,wR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},yR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};NR=(1n<<256n)-1n});var ki=N(()=>{"use strict"});var Na=N(()=>{"use strict"});var Gf=N(()=>{"use strict"});var uc=N(()=>{"use strict";Na()});var Uf=N(()=>{"use strict";Na();uc()});var uk,Kf=N(()=>{"use strict";uk=kr(er(),1);or();ft();Ot()});var HR,Yf=N(()=>{"use strict";or();Ot();HR=4*1024*1024});function fk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Xf(e,t){return(...r)=>{let i=dk;if(i===null)return t(...r);let n=fk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var dk,Qf=N(()=>{"use strict";dk=null});var MR,Zf=N(()=>{"use strict";Qf();ar();MR=Xf("hookWritePolicy",async e=>(await Os(e))?.hook??{allow_paths:[]})});var eh=N(()=>{"use strict";Na();or();Gf();Uf();ft();Kf();Ot();ar();Bs();Yf();Zf();Hs();uc()});var th=N(()=>{"use strict";eh();ni()});var HA,rh=N(()=>{"use strict";th();HA=256*1024});var ih=N(()=>{"use strict";rh();ki()});var KA,Si=N(()=>{"use strict";ki();ih();D();$e();KA={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 dc=N(()=>{"use strict";ki();Re();$();Si()});import{createHash as pk}from"node:crypto";import{promises as ba}from"node:fs";import Nt from"node:path";function ch(e,t){let r=Nt.relative(e,t);return Nt.isAbsolute(r)||r===".."||r.startsWith(`..${Nt.sep}`)?null:r.replaceAll("\\","/")||"."}function lh(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function uh(e,t){if(e.length===0||lh(e)||e.includes("\\")||Nt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Nt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function pc(e,t){return pk("sha256").update(`${e}
176
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function cc(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function Qb(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Mf(e){let t=Un(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?Qb(n):void 0;if(a&&!a())return!1;let o=cc(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=cc(r,c,a),o===null||o.size===0)return!1}return cc(r,o,a)?.has(r.length)??!1}}function Zb(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Un(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Un(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=Xb(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(Mf),excludeMatchers:r.map(Mf),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ne(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function gr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Me(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Wf(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=lc.posix.normalize(e);if(r!==e||lc.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function ek(e,t){let r=ye(e,`Native snapshot entry ${t}`);Ne(r,Fb,`Native snapshot entry ${t}`);let i=Wf(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!ya.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Me(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Ub.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function tk(e,t){let r=ye(e,`Native snapshot omission ${t}`);if(Ne(r,qb,`Native snapshot omission ${t}`),!Jb.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!Gb.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Wf(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Me(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function rk(e){let t=ye(e,"Native snapshot omission overflow");if(Ne(t,Wb,"Native snapshot omission overflow"),typeof t.hash!="string"||!ya.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:gr(t.count,"Native snapshot omission overflow count")}}function vr(e,t){let r=ye(e,t);if(Ne(r,Lb,t),typeof r.hash!="string"||!ya.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Me(r.recordCount,`${t} recordCount`),n=Me(r.storedRecordCount,`${t} storedRecordCount`),a=Me(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Ff(e){let t=ye(e,"Native Git selection evidence");if(Ne(t,Bb,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=vr(t.stageBefore,"Native Git selection stageBefore"),i=vr(t.combined,"Native Git selection combined"),n=vr(t.stageAfter,"Native Git selection stageAfter"),a=vr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=vr(t.finalCombined,"Native Git selection finalCombined"),s=vr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!wa(r,n)||!wa(n,a)||!wa(i,o)||!wa(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(t.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 qf(e,t){let r=ye(e,t);if(Ne(r,Mb,t),typeof r.hash!="string"||!ya.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Me(r.visitedNodeCount,`${t} visitedNodeCount`),n=Me(r.recordCount,`${t} recordCount`),a=Me(r.storedRecordCount,`${t} storedRecordCount`),o=Me(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function ik(e){let t=ye(e,"Native physical selection evidence");if(Ne(t,Vb,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=qf(t.before,"Native physical selection before"),i=qf(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Kb(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function zf(e){let t=ye(e,"Native content snapshot manifest");if(Ne(t,jb,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zb.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let g=ye(t.capture,"Native content snapshot capture");if(Ne(g,Hb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=g.gitSelection===void 0?void 0:Ff(g.gitSelection),k=g.physicalSelection===void 0?void 0:ik(g.physicalSelection),T=null;if(g.projection!==void 0){let ie=ye(g.projection,"Native content snapshot projection");if(Ne(ie,Db,"Native content snapshot projection"),ie.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");T={provider:"git",...ie.selection===void 0?{}:{selection:Ff(ie.selection)}}}if(g.provider==="git"){if(k||T)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&T)throw new Error("Native physical-tree capture cannot combine selection and projection");r=T?{provider:"physical-tree",projection:T}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ye(t.limits,"Native content snapshot limits");Ne(i,$b,"Native content snapshot limits");let n={maxFiles:gr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:gr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:gr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:gr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:gr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=ye(t.policy,"Native snapshot policy");if(Ne(g,Ob,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Zb({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(ek),s=t.omitted.map(tk),c=Me(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:rk(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>n.maxFileBytes)||o.reduce((g,R)=>g+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>_b||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(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.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 p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",E=b?.status==="changed"||b?.status==="overflow-and-changed";if(S!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let x={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Yb(x)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return x}function nk(e,t){if(!Tb.test(t))throw new Error(`Invalid Native change name: ${t}`);return lc.join(de(e,t),"baseline-manifest.json")}async function Jf(e,t){let r=nk(e,t),i=xe(e,r);await I(i,r);try{let n=await jf({root:i,file:r,maxBytes:Ib,label:"Native baseline snapshot manifest"});return zf(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var mR,_b,Ib,Tb,jb,$b,Ob,Hb,Db,Bb,Lb,Vb,Mb,Fb,qb,Wb,zb,Jb,Gb,ya,Ub,vR,gR,wR,yR,NR,bi=N(()=>{"use strict";D();fe();Ve();Oe();$();Le();gi();mR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},_b=1e3,Ib=8*1024*1024,Tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$b=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Ob=new Set(["schema","include","exclude","hash"]),Hb=new Set(["provider","gitSelection","physicalSelection","projection"]),Db=new Set(["provider","selection"]),Bb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Lb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Vb=new Set(["schema","status","before","after"]),Mb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Fb=new Set(["path","hash","size","type","gitObjectId"]),qb=new Set(["path","size","type","reason"]),Wb=new Set(["ref","hash","count"]),zb=new Set(["change-created","legacy-migration","explicit"]),Jb=new Set(["file","directory","other"]),Gb=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"]),ya=/^[a-f0-9]{64}$/u,Ub=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,vR=64*1024,gR=64*1024,wR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},yR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};NR=(1n<<256n)-1n});var ki=N(()=>{"use strict"});var Na=N(()=>{"use strict"});var Gf=N(()=>{"use strict"});var uc=N(()=>{"use strict";Na()});var Uf=N(()=>{"use strict";Na();uc()});var uk,Kf=N(()=>{"use strict";uk=kr(er(),1);or();ft();Ot()});var HR,Yf=N(()=>{"use strict";or();Ot();HR=4*1024*1024});function fk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Xf(e,t){return(...r)=>{let i=dk;if(i===null)return t(...r);let n=fk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var dk,Qf=N(()=>{"use strict";dk=null});var MR,Zf=N(()=>{"use strict";Qf();ar();MR=Xf("hookWritePolicy",async e=>(await Os(e))?.hook??{allow_paths:[]})});var eh=N(()=>{"use strict";Na();or();Gf();Uf();ft();Kf();Ot();ar();Bs();Yf();Zf();Hs();uc()});var th=N(()=>{"use strict";eh();ni()});var HA,rh=N(()=>{"use strict";th();HA=256*1024});var ih=N(()=>{"use strict";rh();ki()});var KA,Si=N(()=>{"use strict";ki();ih();D();Oe();KA={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 dc=N(()=>{"use strict";ki();Ae();$();Si()});import{createHash as pk}from"node:crypto";import{promises as ba}from"node:fs";import Nt from"node:path";function ch(e,t){let r=Nt.relative(e,t);return Nt.isAbsolute(r)||r===".."||r.startsWith(`..${Nt.sep}`)?null:r.replaceAll("\\","/")||"."}function lh(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function uh(e,t){if(e.length===0||lh(e)||e.includes("\\")||Nt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Nt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function pc(e,t){return pk("sha256").update(`${e}
177
177
  ${t}`).digest("hex")}async function oh(e,t){let r=await ba.realpath(t),i=await ba.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=hc==="win32"?Nt.normalize(r).toLowerCase():r;return pc(e,`${n}
178
178
  ${i.dev}
179
179
  ${i.ino}
180
- ${i.birthtimeMs}`)}async function sh(e,t){let r=await ba.realpath(t),i=await ba.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=hc==="win32"?Nt.normalize(r).toLowerCase():r;return pc(e,n)}function vk(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function fc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||lh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function dh(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(fc(e.changeBranch,"Native workspace change branch"),fc(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function gk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!ah.test(t.baseCommit)||typeof t.targetCommit!="string"||!ah.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");fc(t.targetBranch,"Native workspace Git target branch")}function ka(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Ei.test(String(t.projectRootId))||!Ei.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");vk(t.capturedAt),uh(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ei.test(String(t.projectRootPathId))||a&&!Ei.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ei.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&gk(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(dh(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function wk(e,t){return Nt.join(de(e,t),"workspace.json")}function yk(e,t){let r=wk(e,t),i=Ee(e,r),n=ch(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:uh(n,"Native workspace file ref")}}async function Nk(e,t){try{let r=yk(e,t),i=await pe({root:r.root,ref:r.ref,maxBytes:mk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bk(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ch(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=Z(e.paths.projectRoot),i=r.isGitWorktree?pi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:pi(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([oh("comet.native.workspace-project-root.v2",e.paths.projectRoot),oh("comet.native.workspace-native-root.v2",e.paths.nativeRoot),sh("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),sh("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&dh(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:pc("comet.native.workspace-session.v2",`${s}
180
+ ${i.birthtimeMs}`)}async function sh(e,t){let r=await ba.realpath(t),i=await ba.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=hc==="win32"?Nt.normalize(r).toLowerCase():r;return pc(e,n)}function vk(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function fc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||lh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function dh(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(fc(e.changeBranch,"Native workspace change branch"),fc(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function gk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!ah.test(t.baseCommit)||typeof t.targetCommit!="string"||!ah.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");fc(t.targetBranch,"Native workspace Git target branch")}function ka(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Ei.test(String(t.projectRootId))||!Ei.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");vk(t.capturedAt),uh(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Ei.test(String(t.projectRootPathId))||a&&!Ei.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Ei.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&gk(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(dh(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function wk(e,t){return Nt.join(de(e,t),"workspace.json")}function yk(e,t){let r=wk(e,t),i=xe(e,r),n=ch(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:uh(n,"Native workspace file ref")}}async function Nk(e,t){try{let r=yk(e,t),i=await me({root:r.root,ref:r.ref,maxBytes:mk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bk(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=ch(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=Z(e.paths.projectRoot),i=r.isGitWorktree?pi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:pi(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([oh("comet.native.workspace-project-root.v2",e.paths.projectRoot),oh("comet.native.workspace-native-root.v2",e.paths.nativeRoot),sh("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),sh("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&dh(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:pc("comet.native.workspace-session.v2",`${s}
181
181
  ${c}
182
- ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ka(p),p}async function wr(e,t){let r=await Nk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ka(r),r)}async function Sa(e){ka(e.identity);let t=await bk({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),hc==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function Ea(e){if(ka(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Sa(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=Z(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function fh(e,t){let r=await wr(e,t);if(r===null)return null;let i=await Ea({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var Ei,ah,mk,hc,xa=N(()=>{"use strict";yt();D();Oe();Re();$();Ei=/^[a-f0-9]{64}$/u,ah=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,mk=16*1024,hc=process.platform});import{promises as Ca}from"fs";import re from"path";function Ci(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wh(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function _a(e){if(!gh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function _k(e){if(!gh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function yh(e,t){if(e.length===0||re.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Ik(e,t){let r=Ci(e,`spec_changes[${t}]`);if(wh(r,xk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(_k(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"&&yh(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"||!vc.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"||!vc.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 Tk(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function wc(e,t){if(wh(e,t,Ze),typeof e.name!="string")throw new Error("Native change name is required");if(_a(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!Ck.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!Pk.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(Ik),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!Rk.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&yh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Tk(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ca(e){let t=Ci(e,Ze);if(t.schema!==Ye)throw new Error(`Expected ${Ye}`);return{schema:Ye,...wc(t,Sk)}}function xi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Ak.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function jk(e){if(e==null)return null;if(typeof e!="string"||!vc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function $k(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function la(e){let t=Ci(e,Ze);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);if(xi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ke} minimum_runtime_version must be 2`);return{schema:Ke,minimum_runtime_version:2,revision:xi(t.revision,"Native v2 revision"),...wc(t,vh)}}function ua(e){let t=Ci(e,Ze);if(t.schema!==Ue){if(t.schema===Ye||t.schema===Ke){let o=t.schema===Ye?ca(t):la(t);throw new Pa(o.name,o.schema)}throw new Vt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Vt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=xi(t.revision,"Native revision"),n=wc(t,Ek),a=jk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ue,minimum_runtime_version:3,revision:i,verification_protocol:$k(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:mc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:mc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:mc(t.partial_allowance,"Native partial_allowance","allowances")}}function Nh(e){let t=Ci(e,Ze);if(t.schema===Ye){let n=ca(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(t.schema===Ke){let n=la(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(t.schema!==Ue){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Vt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Vt(t.schema,r).message};let i=ua(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function kt(e,t){_a(t);let r=re.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}async function yc(e,t){let r=de(e,t),i=re.join(r,"schema-migration.json");await I(z(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ca.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function bh(e,t=re.dirname(e)){let r=re.relative(t,e).split(re.sep).join("/"),i=await pe({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,gc.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Ok(e,t){let r=re.join(kt(e,t),Ze);await I(e.nativeRoot,r);let i=Nh(await bh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await yc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await Dk(e,i.state),i)}async function Hk(e,t){let r=re.join(kt(e,t),Ze);await I(e.nativeRoot,r);let i=Nh(await bh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function Dk(e,t){if(await Jf(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function St(e,t){let r=await Ok(e,t);if(r.status==="migration-required")throw new Pa(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Vt(r.schema,r.minimumRuntimeVersion);return await fh(e,t),r.state}async function Bk(e){let t;try{let i=await Ni({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),t=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function kh(e){let t=[];for(let r of await Bk(e)){let i=await Hk(e,r);if(!i.state){if(await ph(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await wr(e,r);if(!(!n&&await ph(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await Ea({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Sa({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}function hh(e,t){let r=re.resolve(e),i=re.resolve(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function ph(e,t){for(let r of dr(e.projectRoot))if(!hh(r,e.projectRoot))try{let i=await G(r);if(!i)continue;let n=await Je(r,i.native.artifact_root),a=re.join(n.changesDir,t),o=re.join(a,"comet-state.yaml");try{let l=await Ca.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ca.readFile(re.join(vt(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&hh(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Ca.access(re.join(a,Ze));let s=await wr(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Ea({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Sa({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var gc,mh,Sk,vh,Ek,xk,Ck,Pk,Rk,Ze,vc,gh,Ak,Pa,Vt,Ra,yr,Aa,$_,Y=N(()=>{"use strict";gc=kr(er(),1);yt();Oe();D();Dt();fe();Re();$();Be();Vf();bi();dc();xa();sa();mh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Sk=new Set(mh),vh=new Set([...mh,"minimum_runtime_version","revision"]),Ek=new Set([...vh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),xk=new Set(["capability","operation","source","base_hash"]),Ck=new Set(["shape","build","verify","archive"]),Pk=new Set(["implicit","confirmed"]),Rk=new Set(["pending","pass","fail"]),Ze="comet-state.yaml",vc=/^[a-f0-9]{64}$/u,gh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ak=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Pa=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"},Vt=class extends Error{constructor(r,i){super(r!==Ue||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"},yr=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"},Aa=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"},$_=mi("en")});import{execFileSync as Mk}from"node:child_process";function Wk(e,t){try{return Mk("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Fk,maxBuffer:qk,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Nc(e,t,i)}}function Ae(e,t){return Wk(e,t).trim()}function Sh(e){return Ae(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function bc(e,t){Ae(e,["check-ref-format","--branch",t])}var Fk,qk,Nc,Pi=N(()=>{"use strict";Fk=3e4,qk=8*1024*1024,Nc=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}});import{createHash as zk}from"node:crypto";import{lstatSync as K_,readFileSync as Y_,promises as Eh}from"node:fs";import kc from"node:path";async function Ia(e){let t=kc.join(e,Jk),r;try{r=await Eh.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=Gk(e);await Eh.mkdir(kc.dirname(i),{recursive:!0}),await oe(i,{hash:Uk(r)},{containedRoot:e})}var Jk,Gk,Uk,Ta=N(()=>{"use strict";Pi();D();Jk=".comet/config.yaml",Gk=e=>kc.join(e,".comet","runtime","native","workspace-config.json"),Uk=e=>zk("sha256").update(e).digest("hex")});var tI,ja=N(()=>{"use strict";tI=["$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 Sc=N(()=>{"use strict"});var Mt=N(()=>{"use strict"});var Ec=N(()=>{"use strict";ja();Sc();Mt()});var Ai=N(()=>{"use strict"});var $a=N(()=>{"use strict";Ai()});var xh=N(()=>{"use strict"});var vI,Ch=N(()=>{"use strict";ja();vI=8*1024*1024});var Ph=N(()=>{"use strict";Ch()});import{promises as _i}from"node:fs";import J from"node:path";function xc(e,t){let r=J.normalize(e),i=J.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function _h(e,t){let r=J.relative(e,t);return r===""||!J.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${J.sep}`)}function Rh(e){return JSON.stringify(e.native)}async function Oa(e,t){let r=await G(e);if(r&&t){if(Rh(r)!==Rh(t))throw new Error(`Native worktree configuration differs from the source project: ${J.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await ui(e,t),await Ia(e),!0):!1}async function Qk(e,t){if(!_h(e,t))return!1;let i=`/${J.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=Ae(e,["rev-parse","--git-common-dir"]),a=J.resolve(e,n),o=J.join(a,"info","exclude"),s="";try{s=await _i.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await _i.mkdir(J.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
182
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ka(p),p}async function wr(e,t){let r=await Nk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ka(r),r)}async function Sa(e){ka(e.identity);let t=await bk({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),hc==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function Ea(e){if(ka(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Sa(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=Z(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function fh(e,t){let r=await wr(e,t);if(r===null)return null;let i=await Ea({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var Ei,ah,mk,hc,xa=N(()=>{"use strict";yt();D();He();Ae();$();Ei=/^[a-f0-9]{64}$/u,ah=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,mk=16*1024,hc=process.platform});import{promises as Ca}from"fs";import re from"path";function Ci(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wh(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function _a(e){if(!gh.test(e))throw new Error(`Invalid Native change name: ${e}`)}function _k(e){if(!gh.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function yh(e,t){if(e.length===0||re.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Ik(e,t){let r=Ci(e,`spec_changes[${t}]`);if(wh(r,xk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(_k(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"&&yh(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"||!vc.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"||!vc.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 Tk(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function wc(e,t){if(wh(e,t,Ze),typeof e.name!="string")throw new Error("Native change name is required");if(_a(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!Ck.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!Pk.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(Ik),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!Rk.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&yh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Tk(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ca(e){let t=Ci(e,Ze);if(t.schema!==Ye)throw new Error(`Expected ${Ye}`);return{schema:Ye,...wc(t,Sk)}}function xi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function mc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Ak.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function jk(e){if(e==null)return null;if(typeof e!="string"||!vc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function $k(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function la(e){let t=Ci(e,Ze);if(t.schema!==Ke)throw new Error(`Expected ${Ke}`);if(xi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ke} minimum_runtime_version must be 2`);return{schema:Ke,minimum_runtime_version:2,revision:xi(t.revision,"Native v2 revision"),...wc(t,vh)}}function ua(e){let t=Ci(e,Ze);if(t.schema!==Ue){if(t.schema===Ye||t.schema===Ke){let o=t.schema===Ye?ca(t):la(t);throw new Pa(o.name,o.schema)}throw new Vt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Vt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=xi(t.revision,"Native revision"),n=wc(t,Ek),a=jk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ue,minimum_runtime_version:3,revision:i,verification_protocol:$k(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:mc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:mc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:mc(t.partial_allowance,"Native partial_allowance","allowances")}}function Nh(e){let t=Ci(e,Ze);if(t.schema===Ye){let n=ca(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(t.schema===Ke){let n=la(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(t.schema!==Ue){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Vt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=xi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Vt(t.schema,r).message};let i=ua(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function kt(e,t){_a(t);let r=re.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}async function yc(e,t){let r=de(e,t),i=re.join(r,"schema-migration.json");await I(z(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ca.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function bh(e,t=re.dirname(e)){let r=re.relative(t,e).split(re.sep).join("/"),i=await me({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,gc.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Ok(e,t){let r=re.join(kt(e,t),Ze);await I(e.nativeRoot,r);let i=Nh(await bh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await yc(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await Dk(e,i.state),i)}async function Hk(e,t){let r=re.join(kt(e,t),Ze);await I(e.nativeRoot,r);let i=Nh(await bh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function Dk(e,t){if(await Jf(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function St(e,t){let r=await Ok(e,t);if(r.status==="migration-required")throw new Pa(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Vt(r.schema,r.minimumRuntimeVersion);return await fh(e,t),r.state}async function Bk(e){let t;try{let i=await Ni({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),t=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function kh(e){let t=[];for(let r of await Bk(e)){let i=await Hk(e,r);if(!i.state){if(await ph(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await wr(e,r);if(!(!n&&await ph(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await Ea({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await Sa({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}function hh(e,t){let r=re.resolve(e),i=re.resolve(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function ph(e,t){for(let r of dr(e.projectRoot))if(!hh(r,e.projectRoot))try{let i=await G(r);if(!i)continue;let n=await Ge(r,i.native.artifact_root),a=re.join(n.changesDir,t),o=re.join(a,"comet-state.yaml");try{let l=await Ca.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ca.readFile(re.join(vt(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&hh(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Ca.access(re.join(a,Ze));let s=await wr(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Ea({paths:n,identity:s})).state==="aligned")return!0;continue}if((await Sa({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var gc,mh,Sk,vh,Ek,xk,Ck,Pk,Rk,Ze,vc,gh,Ak,Pa,Vt,Ra,yr,Aa,$_,Y=N(()=>{"use strict";gc=kr(er(),1);yt();He();D();Dt();fe();Ae();$();Le();Vf();bi();dc();xa();sa();mh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Sk=new Set(mh),vh=new Set([...mh,"minimum_runtime_version","revision"]),Ek=new Set([...vh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),xk=new Set(["capability","operation","source","base_hash"]),Ck=new Set(["shape","build","verify","archive"]),Pk=new Set(["implicit","confirmed"]),Rk=new Set(["pending","pass","fail"]),Ze="comet-state.yaml",vc=/^[a-f0-9]{64}$/u,gh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ak=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Pa=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"},Vt=class extends Error{constructor(r,i){super(r!==Ue||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"},yr=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"},Aa=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"},$_=mi("en")});import{execFileSync as Mk}from"node:child_process";function Wk(e,t){try{return Mk("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Fk,maxBuffer:qk,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Nc(e,t,i)}}function _e(e,t){return Wk(e,t).trim()}function Sh(e){return _e(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function bc(e,t){_e(e,["check-ref-format","--branch",t])}var Fk,qk,Nc,Pi=N(()=>{"use strict";Fk=3e4,qk=8*1024*1024,Nc=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}});import{createHash as zk}from"node:crypto";import{lstatSync as K_,readFileSync as Y_,promises as Eh}from"node:fs";import kc from"node:path";async function Ia(e){let t=kc.join(e,Jk),r;try{r=await Eh.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=Gk(e);await Eh.mkdir(kc.dirname(i),{recursive:!0}),await oe(i,{hash:Uk(r)},{containedRoot:e})}var Jk,Gk,Uk,Ta=N(()=>{"use strict";Pi();D();Jk=".comet/config.yaml",Gk=e=>kc.join(e,".comet","runtime","native","workspace-config.json"),Uk=e=>zk("sha256").update(e).digest("hex")});var tI,ja=N(()=>{"use strict";tI=["$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 Sc=N(()=>{"use strict"});var Mt=N(()=>{"use strict"});var Ec=N(()=>{"use strict";ja();Sc();Mt()});var Ai=N(()=>{"use strict"});var $a=N(()=>{"use strict";Ai()});var xh=N(()=>{"use strict"});var vI,Ch=N(()=>{"use strict";ja();vI=8*1024*1024});var Ph=N(()=>{"use strict";Ch()});import{promises as _i}from"node:fs";import J from"node:path";function xc(e,t){let r=J.normalize(e),i=J.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function _h(e,t){let r=J.relative(e,t);return r===""||!J.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${J.sep}`)}function Rh(e){return JSON.stringify(e.native)}async function Oa(e,t){let r=await G(e);if(r&&t){if(Rh(r)!==Rh(t))throw new Error(`Native worktree configuration differs from the source project: ${J.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await ui(e,t),await Ia(e),!0):!1}async function Qk(e,t){if(!_h(e,t))return!1;let i=`/${J.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=_e(e,["rev-parse","--git-common-dir"]),a=J.resolve(e,n),o=J.join(a,"info","exclude"),s="";try{s=await _i.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await _i.mkdir(J.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
183
183
  `)?"":`
184
184
  `;return await _i.appendFile(o,`${c}${i}
185
- `,"utf8"),!0}function Zk(e,t,r){let i=J.resolve(e,r??J.join(".worktrees",t)),n=J.resolve(e,Ae(e,["rev-parse","--git-common-dir"]));if(_h(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(dr(e).some(a=>xc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function eS(e){try{throw await _i.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Ah(e){try{return await _i.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Cc(e){let t=J.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=Z(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Je(t,e.sourceConfig?.native.artifact_root??"docs");return hf([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=Z(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;bc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(bc(t,o),!fr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Sh(t))throw new Error("Native branch isolation requires a clean current working directory");if(fr(t,n))throw new Error(`Native change branch already exists: ${n}`);Ae(t,["switch","-c",n,o]),p=!0}let v;try{v=await Oa(t,e.sourceConfig)}catch(h){throw new Et(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?J.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!xc(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Oa(t,e.sourceConfig)}catch(h){throw new Et(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=Yn(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await Ah(c.root)){let p=e.worktreePath?J.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!xc(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Oa(c.root,e.sourceConfig)}catch(h){throw new Et(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Ah(c.root)&&(Ae(i.primaryWorktreeRoot,["worktree","prune"]),s=Yn(i.primaryWorktreeRoot));let l=fr(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=Zk(i.primaryWorktreeRoot,e.name,e.worktreePath);await eS(u);let d=await Qk(i.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{Ae(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Oa(u,e.sourceConfig)}catch(p){throw new Et(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var Et,Ha=N(()=>{"use strict";Pi();yt();fe();Ta();wi();$();Et=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});var Pc=N(()=>{"use strict";Ta();D();te();Ec();$a();Re();$();fe();yt();xh();Pi();Ph();Ha()});var oS,Ih=N(()=>{"use strict";oS=kr(er(),1);yt();Pi();Oe();te();fe();$();yi();Pc()});var Hh,Nr=N(()=>{"use strict";te();bi();Hh=1024*1024});var Ma=N(()=>{"use strict";te();Mt();gi();Nr()});var Bh,mS,vS,gS,IT,wS,TT,_c=N(()=>{"use strict";te();Bh="scoped-text-safety",mS=1,vS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),gS="comet.native.checker-policy.v1",IT=ee(gS,{policy:Bh,version:mS,limits:vS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),wS=["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"],TT=new Set(wS)});var Fa=N(()=>{"use strict";te();_c();Mt()});var bS,KT,br=N(()=>{"use strict";D();$();$e();Nr();Ma();Fa();bS=Hh,KT=3*bS});fe();$();fi();function Ge(e,t,r){return e.language==="zh-CN"?r:t}function Ly(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Ge(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Ge(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ge(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Ge(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(Ge(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(Ge(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Vy(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function My(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:Ge(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Ge(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Xd(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ht(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Fy(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Yd(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function qy(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function Wy(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function gt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Xd({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ht("summary","--summary"),Fy(e.name,e.flag)]}}function Ws(e){return[gt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),gt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Qd(e,t,r={}){let i=qy(t)&&e.coordination_mode===void 0,n=Ly(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ws({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),gt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ws({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:Ws({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Xd({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:Wy({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Yd("coordination-mode","--coordination-mode",Kd)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=t.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[Ht("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Ge(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Yd("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...My(e)],userCommunication:Vy(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[gt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}yt();D();import{promises as xt}from"node:fs";import Ti from"node:path";Dt();Y();Oe();Le();$();var Vk=["outcome","scope","nonGoals","acceptanceExamples"],F_=[...Vk,"constraints","decisions","openQuestions","verificationExpectations"];Oe();te();Ih();Pc();Y();Ec();yi();oa();Ai();$a();D();fi();import{promises as lS}from"node:fs";import Ii from"node:path";function Da(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ba(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Me(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Th(e,t){return e===null?null:Me(e,t)}function Va(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function uS(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function dS(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function La(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Rc(e,t){if(e===null)return null;let r=Me(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Ac(e,t){let r=Me(e,t);if(!Ii.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ii.resolve(r)}function fS(e,t){let r=`Native local checks[${t}]`,i=Da(e,r);if(Ba(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Me(l,`${r}.argv[${u}]`,!0)),a=La(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Rc(i.startedAt,`${r}.startedAt`),s=Rc(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Va(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Me(i.id,`${r}.id`),name:Me(i.name,`${r}.name`),operationId:Me(i.operationId,`${r}.operationId`),status:a,repeatable:dS(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Va(i.executionCount,`${r}.executionCount`),argv:n,cwd:Ac(i.cwd,`${r}.cwd`),exitCode:uS(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Me(i.log,`${r}.log`)}}function jh(e){let t="Native local execution state",r=Da(e,t);if(Ba(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==di)throw new Error(`Native local execution schema must be ${di}`);let i=Da(r.workspace,"Native local workspace");Ba(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Da(r.execution,"Native local execution");Ba(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Rc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Me(o.operationId,"Native local execution.operationId"),stage:La(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:La(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Th(o.executionId,"Native local execution.executionId"),status:La(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Va(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(fS);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:di,change:Me(r.change,"Native local change"),basedOnStateVersion:Va(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ac(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ac(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Th(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function $h(e){return jh({schema:di,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ii.resolve(e.projectRoot),worktreeRoot:Ii.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Oh(e,t,r={}){let i=jh(t);await lS.mkdir(Ii.dirname(e),{recursive:!0}),await oe(e,i,r)}Re();Qs();yi();ic();oa();Ai();$a();D();Dt();Ai();$();Dt();br();fe();var Lh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SS="comet-state.yaml",ES="state.json",s$=mi("en");function Vh(e,t){if(!Lh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Ti.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ic(e,t){return Ti.join(Vh(e,t),SS)}function xS(e,t){return Ti.join(vt(e,t),ES)}async function Mh(e,t){try{let r=await xt.readFile(Ic(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function CS(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function PS(e){return Z(e).currentBranch}function RS(e,t){if(!t)return;let r=Z(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Fh(e){return ge(e.paths,`create portable change ${e.name}`,async()=>{if(!Lh.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await G(e.paths.projectRoot)===null&&await ui(e.paths.projectRoot,e.initialProjectConfig),RS(e.paths.projectRoot,e.workspaceBinding);let t=(await kh(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new yr(e.workspaceBinding?.isolation??"current",t);let r=Vh(e.paths,e.name),i=vt(e.paths,e.name);await Promise.all([I(e.paths.nativeRoot,r),I(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await xt.mkdir(e.paths.changesDir,{recursive:!0}),await xt.mkdir(r,{recursive:!1}),n=!0,await xt.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await xt.mkdir(i,{recursive:!1}),a=!0,await xt.mkdir(Ti.join(r,"specs"),{recursive:!0}),await ue(Ti.join(r,"brief.md"),mi(e.language));let o=wf({name:e.name,language:e.language,workspace:CS(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await yf(Ic(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await Oh(xS(e.paths,e.name),$h({portableState:o,projectRoot:e.paths.projectRoot,branch:PS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await xt.rm(i,{recursive:!0,force:!0}),n&&await xt.rm(r,{recursive:!0,force:!0}),o}})}async function qh(e,t){return tc(Ic(e,t))}oi();import{randomUUID as AS}from"crypto";import{promises as qa}from"fs";import zh from"path";var Tc="comet.selection.v2",h$=16*1024;function Jh(e){return zh.join(e,".comet","current-change.json")}function _S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wh(e){return e===null||typeof e=="string"}function IS(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!_S(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Wh(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Tc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Tc)throw new Error(`current change selection schema must be ${Tc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Wh(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Gh(e,t){let r=IS(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Jh(e),n=`${i}.${AS()}.tmp`;await qa.mkdir(zh.dirname(i),{recursive:!0});try{await qa.writeFile(n,`${JSON.stringify(r.selection,null,2)}
186
- `,"utf8"),await qa.rename(n,i)}catch(a){throw await qa.rm(n,{force:!0}),a}}Y();fe();Re();var S$=16*1024;async function Uh(e,t){return ge(e,`select change ${t}`,async()=>{_a(t),await Mh(e,t)?await qh(e,t):await St(e,t),await Gh(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}Ha();Ta();oi();import $i from"path";import{realpathSync as gE}from"fs";yt();var et={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Kh(e){return e?e.command?`${et.next} ${e.command}`:e.ask_user?`${et.next} ${e.ask_user}`:null:null}function Yh(e,t){let r=[e.summary],i=Kh(e.next);return i&&r.push(i),e.user_message&&r.push("",et.relay,e.user_message),t!==void 0&&r.push("",et.details,JSON.stringify(t,null,2)),`${r.join(`
185
+ `,"utf8"),!0}function Zk(e,t,r){let i=J.resolve(e,r??J.join(".worktrees",t)),n=J.resolve(e,_e(e,["rev-parse","--git-common-dir"]));if(_h(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(dr(e).some(a=>xc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function eS(e){try{throw await _i.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Ah(e){try{return await _i.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Cc(e){let t=J.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=Z(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Ge(t,e.sourceConfig?.native.artifact_root??"docs");return hf([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=Z(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;bc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(bc(t,o),!fr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Sh(t))throw new Error("Native branch isolation requires a clean current working directory");if(fr(t,n))throw new Error(`Native change branch already exists: ${n}`);_e(t,["switch","-c",n,o]),p=!0}let v;try{v=await Oa(t,e.sourceConfig)}catch(h){throw new Et(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?J.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!xc(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Oa(t,e.sourceConfig)}catch(h){throw new Et(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=Yn(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await Ah(c.root)){let p=e.worktreePath?J.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!xc(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Oa(c.root,e.sourceConfig)}catch(h){throw new Et(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Ah(c.root)&&(_e(i.primaryWorktreeRoot,["worktree","prune"]),s=Yn(i.primaryWorktreeRoot));let l=fr(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=Zk(i.primaryWorktreeRoot,e.name,e.worktreePath);await eS(u);let d=await Qk(i.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{_e(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Oa(u,e.sourceConfig)}catch(p){throw new Et(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var Et,Ha=N(()=>{"use strict";Pi();yt();fe();Ta();wi();$();Et=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});var Pc=N(()=>{"use strict";Ta();D();te();Ec();$a();Ae();$();fe();yt();xh();Pi();Ph();Ha()});var oS,Ih=N(()=>{"use strict";oS=kr(er(),1);yt();Pi();He();te();fe();$();yi();Pc()});var Hh,Nr=N(()=>{"use strict";te();bi();Hh=1024*1024});var Ma=N(()=>{"use strict";te();Mt();gi();Nr()});var Bh,mS,vS,gS,IT,wS,TT,_c=N(()=>{"use strict";te();Bh="scoped-text-safety",mS=1,vS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),gS="comet.native.checker-policy.v1",IT=ee(gS,{policy:Bh,version:mS,limits:vS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),wS=["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"],TT=new Set(wS)});var Fa=N(()=>{"use strict";te();_c();Mt()});var bS,KT,br=N(()=>{"use strict";D();$();Oe();Nr();Ma();Fa();bS=Hh,KT=3*bS});fe();$();fi();function he(e,t,r){return e.language==="zh-CN"?r:t}function Ly(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:he(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:he(e,"Reply A or B","回复 A 或 B"),agentInstruction:he(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(he(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(he(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{required:!0,message:he(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:he(e,"Accept the result","接受结果"),agentInstruction:he(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")}:r(he(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Vy(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function My(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:he(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:he(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Xd(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ht(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Fy(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Yd(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function qy(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function Wy(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function gt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Xd({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ht("summary","--summary"),Fy(e.name,e.flag)]}}function Ws(e){return[gt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),gt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Qd(e,t,r={}){let i=qy(t)&&e.coordination_mode===void 0,n=Ly(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ws({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),gt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:[gt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ws({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Ht("summary","--summary")],commandAlternatives:Ws({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Xd({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:Wy({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Yd("coordination-mode","--coordination-mode",Kd)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=t.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[Ht("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${he(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Yd("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...My(e)],userCommunication:Vy(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[gt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}yt();D();import{promises as xt}from"node:fs";import Ti from"node:path";Dt();Y();He();Ve();$();var Vk=["outcome","scope","nonGoals","acceptanceExamples"],F_=[...Vk,"constraints","decisions","openQuestions","verificationExpectations"];He();te();Ih();Pc();Y();Ec();yi();oa();Ai();$a();D();fi();import{promises as lS}from"node:fs";import Ii from"node:path";function Da(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ba(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Fe(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Th(e,t){return e===null?null:Fe(e,t)}function Va(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function uS(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function dS(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function La(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Rc(e,t){if(e===null)return null;let r=Fe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Ac(e,t){let r=Fe(e,t);if(!Ii.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ii.resolve(r)}function fS(e,t){let r=`Native local checks[${t}]`,i=Da(e,r);if(Ba(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Fe(l,`${r}.argv[${u}]`,!0)),a=La(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Rc(i.startedAt,`${r}.startedAt`),s=Rc(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Va(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Fe(i.id,`${r}.id`),name:Fe(i.name,`${r}.name`),operationId:Fe(i.operationId,`${r}.operationId`),status:a,repeatable:dS(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Va(i.executionCount,`${r}.executionCount`),argv:n,cwd:Ac(i.cwd,`${r}.cwd`),exitCode:uS(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Fe(i.log,`${r}.log`)}}function jh(e){let t="Native local execution state",r=Da(e,t);if(Ba(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==di)throw new Error(`Native local execution schema must be ${di}`);let i=Da(r.workspace,"Native local workspace");Ba(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Da(r.execution,"Native local execution");Ba(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Rc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Fe(o.operationId,"Native local execution.operationId"),stage:La(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:La(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Th(o.executionId,"Native local execution.executionId"),status:La(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Va(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(fS);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:di,change:Fe(r.change,"Native local change"),basedOnStateVersion:Va(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ac(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ac(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Th(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function $h(e){return jh({schema:di,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ii.resolve(e.projectRoot),worktreeRoot:Ii.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Oh(e,t,r={}){let i=jh(t);await lS.mkdir(Ii.dirname(e),{recursive:!0}),await oe(e,i,r)}Ae();Qs();yi();ic();oa();Ai();$a();D();Dt();Ai();$();Dt();br();fe();var Lh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SS="comet-state.yaml",ES="state.json",s$=mi("en");function Vh(e,t){if(!Lh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Ti.join(e.changesDir,t);if(!z(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ic(e,t){return Ti.join(Vh(e,t),SS)}function xS(e,t){return Ti.join(vt(e,t),ES)}async function Mh(e,t){try{let r=await xt.readFile(Ic(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function CS(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function PS(e){return Z(e).currentBranch}function RS(e,t){if(!t)return;let r=Z(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Fh(e){return we(e.paths,`create portable change ${e.name}`,async()=>{if(!Lh.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await G(e.paths.projectRoot)===null&&await ui(e.paths.projectRoot,e.initialProjectConfig),RS(e.paths.projectRoot,e.workspaceBinding);let t=(await kh(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new yr(e.workspaceBinding?.isolation??"current",t);let r=Vh(e.paths,e.name),i=vt(e.paths,e.name);await Promise.all([I(e.paths.nativeRoot,r),I(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await xt.mkdir(e.paths.changesDir,{recursive:!0}),await xt.mkdir(r,{recursive:!1}),n=!0,await xt.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await xt.mkdir(i,{recursive:!1}),a=!0,await xt.mkdir(Ti.join(r,"specs"),{recursive:!0}),await ue(Ti.join(r,"brief.md"),mi(e.language));let o=wf({name:e.name,language:e.language,workspace:CS(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await yf(Ic(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await Oh(xS(e.paths,e.name),$h({portableState:o,projectRoot:e.paths.projectRoot,branch:PS(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await xt.rm(i,{recursive:!0,force:!0}),n&&await xt.rm(r,{recursive:!0,force:!0}),o}})}async function qh(e,t){return tc(Ic(e,t))}oi();import{randomUUID as AS}from"crypto";import{promises as qa}from"fs";import zh from"path";var Tc="comet.selection.v2",h$=16*1024;function Jh(e){return zh.join(e,".comet","current-change.json")}function _S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wh(e){return e===null||typeof e=="string"}function IS(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!_S(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Wh(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Tc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Tc)throw new Error(`current change selection schema must be ${Tc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Wh(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Gh(e,t){let r=IS(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Jh(e),n=`${i}.${AS()}.tmp`;await qa.mkdir(zh.dirname(i),{recursive:!0});try{await qa.writeFile(n,`${JSON.stringify(r.selection,null,2)}
186
+ `,"utf8"),await qa.rename(n,i)}catch(a){throw await qa.rm(n,{force:!0}),a}}Y();fe();Ae();var S$=16*1024;async function Uh(e,t){return we(e,`select change ${t}`,async()=>{_a(t),await Mh(e,t)?await qh(e,t):await St(e,t),await Gh(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}Ha();Ta();oi();import $i from"path";import{realpathSync as gE}from"fs";yt();var et={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Kh(e){return e?e.command?`${et.next} ${e.command}`:e.ask_user?`${et.next} ${e.ask_user}`:null:null}function Yh(e,t){let r=[e.summary],i=Kh(e.next);return i&&r.push(i),e.user_message&&r.push("",et.relay,e.user_message),t!==void 0&&r.push("",et.details,JSON.stringify(t,null,2)),`${r.join(`
187
187
  `)}
188
188
  `}function Xh(e,t,r){let i=[e.summary],n=Kh(e.next);return n&&i.push(n),e.user_message&&i.push("",et.relay,e.user_message),i.push("",`${et.detail} ${t}`),r!==void 0&&i.push("",et.details,JSON.stringify(r,null,2)),i.join(`
189
- `)}Si();te();Oe();Y();te();var TS=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});br();Be();xa();Y();fe();$();ki();D();Y();Le();wi();Re();$();Be();Mt();te();te();Ma();Nr();Le();var Qh={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:[]},$S=ce("comet-native-runtime:v3:scope-reopen"),dO=[{skillVersion:"3",skillHash:ce("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ce("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ce("comet-native-runtime:v1")}];Si();Le();Si();Le();dc();sa();var ep=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],zO=new Set(ep),VS=new Set([...ep,"minimum_runtime_version","revision"]),JO=new Set([...VS,"operation"]),GO=512*1024,MS=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),UO=new Set([...MS,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);ia();Oe();Y();Oe();ia();te();var ZO={maxAcceptanceCriteria:mf.maxCriteria};var n0={maxSpecs:64,maxFileBytes:Qn,maxTotalBytes:4*1024*1024};br();bi();Nr();Ma();import{execFile as YS}from"node:child_process";ja();Sc();Y();import{promisify as XS}from"node:util";Y();D();Y();Le();$();Be();gi();Mt();var p0={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};Re();D();_c();$();$e();var O0=512*1024;br();Re();Mt();var ji=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};bi();Fa();Nr();var nH=64*1024;var aH=3600*1e3;var oH=XS(YS);Fa();var Wa=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};xa();Le();Be();var WH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};D();$e();$();Be();ga();var eD=16*1024*1024,tD=256*1024,rD=16*1024;Y();D();Dt();Y();br();var cD=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Le();wi();Re();$();Be();ga();var QD=16*1024*1024,za=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"},Ja=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"};Y();$();fe();function C(e,t,r){return e==="zh-CN"?r:t}var jc={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function ip(e,t){return typeof e=="string"&&jc[e]?C(t,jc[e].en,jc[e].zh):typeof e=="string"?e:""}function $c(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function iE(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function np(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function ap(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Oc(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function nE(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function aE(e,t,r){let i=Oc(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=ip(e.phase,i),s=nE(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(np(t,i));let c=e.userCommunication,l=op(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function op(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function oE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function sE(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=ip(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=$c(e.acceptance)?`${C(t,", ",",")}${np(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function cE(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function lE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function uE(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=dE(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.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 dE(e){return ap(e)?op(e,Oc(e)):void 0}function sp(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(lE(t))return uE(t);if(oE(t)){let i=cE(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>sE(a,i))].join(`
190
- `)}}let r=t.continuation;if(ap(r))return aE(r,fE(t),hE(t,Oc(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:C(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function fE(e){if($c(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if($c(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return iE(r.acceptance)}return null}function hE(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function cp(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.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}}Ha();var lp=["--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."],Dc=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:lp,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>
191
- 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>]
189
+ `)}Si();te();He();Y();te();var TS=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});br();Le();xa();Y();fe();$();ki();D();Y();Ve();wi();Ae();$();Le();Mt();te();te();Ma();Nr();Ve();var Qh={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:[]},$S=ce("comet-native-runtime:v3:scope-reopen"),dO=[{skillVersion:"3",skillHash:ce("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ce("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ce("comet-native-runtime:v1")}];Si();Ve();Si();Ve();dc();sa();var ep=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],zO=new Set(ep),VS=new Set([...ep,"minimum_runtime_version","revision"]),JO=new Set([...VS,"operation"]),GO=512*1024,MS=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),UO=new Set([...MS,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);ia();He();Y();He();ia();te();var ZO={maxAcceptanceCriteria:mf.maxCriteria};var n0={maxSpecs:64,maxFileBytes:Qn,maxTotalBytes:4*1024*1024};br();bi();Nr();Ma();import{execFile as YS}from"node:child_process";ja();Sc();Y();import{promisify as XS}from"node:util";Y();D();Y();Ve();$();Le();gi();Mt();var p0={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};Ae();D();_c();$();Oe();var O0=512*1024;br();Ae();Mt();var ji=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};bi();Fa();Nr();var nH=64*1024;var aH=3600*1e3;var oH=XS(YS);Fa();var Wa=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};xa();Ve();Le();var WH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};D();Oe();$();Le();ga();var eD=16*1024*1024,tD=256*1024,rD=16*1024;Y();D();Dt();Y();br();var cD=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ve();wi();Ae();$();Le();ga();var QD=16*1024*1024,za=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"},Ja=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"};Y();$();fe();function C(e,t,r){return e==="zh-CN"?r:t}var jc={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function ip(e,t){return typeof e=="string"&&jc[e]?C(t,jc[e].en,jc[e].zh):typeof e=="string"?e:""}function $c(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function iE(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function np(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function ap(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Oc(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function nE(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function aE(e,t,r){let i=Oc(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=ip(e.phase,i),s=nE(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(np(t,i));let c=e.userCommunication,l=op(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function op(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function oE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function sE(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=ip(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=$c(e.acceptance)?`${C(t,", ",",")}${np(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function cE(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function lE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function uE(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=dE(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.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 dE(e){return ap(e)?op(e,Oc(e)):void 0}function sp(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(lE(t))return uE(t);if(oE(t)){let i=cE(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>sE(a,i))].join(`
190
+ `)}}let r=t.continuation;if(ap(r))return aE(r,fE(t),hE(t,Oc(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:C(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function fE(e){if($c(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if($c(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return iE(r.acceptance)}return null}function hE(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function cp(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.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}}Ha();var lp=["--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."],Dc=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:lp,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>
191
+ 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>]
192
192
  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>]
193
193
  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]
194
194
  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 Hc(e,t){return`${e}:
@@ -196,12 +196,12 @@ ${t.map(r=>` ${r}`).join(`
196
196
  `)}`}function pE(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Dc[r]||t.length>1&&Dc[t[0]]?.subcommands?r:t[0]}function mE(e=[]){let t=pE(e),r=Dc[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Hc("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...lp];return n&&n.length>0&&i.push("",Hc("Options",n)),i.push("",`Output:
197
197
  ${r.output}`),r.examples&&i.push("",Hc("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
198
198
  `)}
199
- `}}var vE=mE().usage;var wB=10*1024*1024,_e=class extends Error{};function Lc(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new _e(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Ct(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new _e(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new _e(`${t} requires a value`);return e.splice(i,2),n}function dp(e){if(e.length>0)throw new _e(`Unexpected argument: ${e[0]}`)}function fp(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new _e(`${t} is required`);return r}function hp(e,t="en"){let r=Ct(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new _e("--language must be en or zh-CN");return r}function Bc(e,t){let r=$i.normalize(up(e)),i=$i.normalize(up(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function up(e){let t=$i.resolve(e);try{return gE.native(t)}catch{return t}}function wE(e){let t=$i.resolve(e),r=Z(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=Z(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Bc(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Bc(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Bc(process.cwd(),r.currentWorktreeRoot)?$i.resolve(process.cwd()):r.currentWorktreeRoot}async function pp(e){return e?wE(e):Ms(process.cwd())}function mp(e){return JSON.stringify(e,null,2)+`
200
- `}function vp(e,t,r){return{command:e,exitCode:0,data:t,text:r??mp(t)}}function yE(e,t){if(t instanceof _e)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof za)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Ja)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ra)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof yr)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Et)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Aa)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Wa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ji)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function gp(e,t){let r=yE(e,t),i=r.error;if(!i)return r;let n=cp({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function wp(e,t,r=!1){let i=e.envelope??sp(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
199
+ `}}var vE=mE().usage;var wB=10*1024*1024,Ie=class extends Error{};function Lc(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Ie(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Ct(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Ie(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Ie(`${t} requires a value`);return e.splice(i,2),n}function dp(e){if(e.length>0)throw new Ie(`Unexpected argument: ${e[0]}`)}function fp(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Ie(`${t} is required`);return r}function hp(e,t="en"){let r=Ct(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new Ie("--language must be en or zh-CN");return r}function Bc(e,t){let r=$i.normalize(up(e)),i=$i.normalize(up(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function up(e){let t=$i.resolve(e);try{return gE.native(t)}catch{return t}}function wE(e){let t=$i.resolve(e),r=Z(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=Z(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Bc(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Bc(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Bc(process.cwd(),r.currentWorktreeRoot)?$i.resolve(process.cwd()):r.currentWorktreeRoot}async function pp(e){return e?wE(e):Ms(process.cwd())}function mp(e){return JSON.stringify(e,null,2)+`
200
+ `}function vp(e,t,r){return{command:e,exitCode:0,data:t,text:r??mp(t)}}function yE(e,t){if(t instanceof Ie)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof za)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Ja)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ra)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof yr)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Et)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Aa)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Wa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ji)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function gp(e,t){let r=yE(e,t),i=r.error;if(!i)return r;let n=cp({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function wp(e,t,r=!1){let i=e.envelope??sp(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
201
201
  `}:e.error?{exitCode:e.exitCode,stderr:i?Xh(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Yh(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==mp(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
202
202
  ${et.details}
203
203
  ${JSON.stringify(e.data,null,2)}
204
- `}:{exitCode:e.exitCode,stdout:e.text}}async function yp(e,t){let r=fp(e,"change name"),i=await G(t),n=hp(e,i?.native.language??"en"),a=Ct(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new _e("--isolation must be current, branch, or worktree");let o=Ct(e,"--change-branch"),s=Ct(e,"--target-branch"),c=Ct(e,"--worktree-path");dp(e);let l=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let u=await Cc({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,i=await G(t);let d=i===null?Ud("docs",n):void 0;if(i||(i=d),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let f=await Je(t,i.native.artifact_root);await Jd(f);let p=await Fh({paths:f,name:r,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await Uh(f,p.name),d&&await Ia(t),vp("new",{...p,preparation:u.preparation,continuation:Qd(p)},`Created Native change ${p.name}
204
+ `}:{exitCode:e.exitCode,stdout:e.text}}async function yp(e,t){let r=fp(e,"change name"),i=await G(t),n=hp(e,i?.native.language??"en"),a=Ct(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new Ie("--isolation must be current, branch, or worktree");let o=Ct(e,"--change-branch"),s=Ct(e,"--target-branch"),c=Ct(e,"--worktree-path");dp(e);let l=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let u=await Cc({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,i=await G(t);let d=i===null?Ud("docs",n):void 0;if(i||(i=d),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let f=await Ge(t,i.native.artifact_root);await Jd(f);let p=await Fh({paths:f,name:r,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await Uh(f,p.name),d&&await Ia(t),vp("new",{...p,preparation:u.preparation,continuation:Qd(p)},`Created Native change ${p.name}
205
205
  `)}async function Np(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Lc(n,"--json"),Lc(n,"--verbose"),c=Ct(n,"--project-root");let d=[...n,...a],f=await pp(c);l=await t(d,f)}catch(d){l=gp(e,d)}let u=wp(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
206
206
  `)?"":`
207
207
  `)),u.exitCode}process.exitCode=await Np("new",yp);