@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,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var lb=Object.create;var Cc=Object.defineProperty;var ub=Object.getOwnPropertyDescriptor;var db=Object.getOwnPropertyNames;var fb=Object.getPrototypeOf,pb=Object.prototype.hasOwnProperty;var za=(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 A=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ep=(e,t)=>{for(var r in t)Cc(e,r,{get:t[r],enumerable:!0})},hb=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of db(t))!pb.call(e,n)&&n!==r&&Cc(e,n,{get:()=>t[n],enumerable:!(i=ub(t,n))||i.enumerable});return e};var fi=(e,t,r)=>(r=e!=null?lb(fb(e)):{},hb(t||!e||!e.__esModule?Cc(r,"default",{value:e,enumerable:!0}):r,e));import{execFileSync as mb}from"child_process";import mn from"path";function pi(e,t){return mb("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function vb(e,t){let r=mn.normalize(e),i=mn.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Ee(e){try{let t=mn.resolve(pi(e,["rev-parse","--show-toplevel"])),i=pi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?mn.resolve(i.slice(9)):t,a=null;try{a=pi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!vb(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function tp(e){try{pi(e,["rev-parse","--is-inside-work-tree"]);let t=pi(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:mn.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 er(e){return tp(e).map(t=>t.root)}function Lr(e,t){try{let r=pi(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 vt=A(()=>{"use strict"});import{createHash as gb}from"crypto";function Ze(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function wb(e,t){t.has(e)&&Ze("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)||Ze("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Ze("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ze("symbol properties are not supported"),`[${e.map(i=>xc(i,t)).join(",")}]`}finally{t.delete(e)}}function yb(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ze("only plain objects are supported"),t.has(e)&&Ze("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ze("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))&&Ze("accessor properties are not supported"),`${JSON.stringify(o)}:${xc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function xc(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)||Ze("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?wb(e,t):yb(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ze(`${typeof e} values are not supported`)}return Ze("unsupported value type")}function vn(e){return xc(e,new Set)}function j(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 gb("sha256").update(`${e}
5
- ${vn(t)}`).digest("hex")}var pe=A(()=>{"use strict"});var q=P(we=>{"use strict";var Pc=Symbol.for("yaml.alias"),rp=Symbol.for("yaml.document"),Ja=Symbol.for("yaml.map"),ip=Symbol.for("yaml.pair"),Rc=Symbol.for("yaml.scalar"),Ga=Symbol.for("yaml.seq"),Tt=Symbol.for("yaml.node.type"),Nb=e=>!!e&&typeof e=="object"&&e[Tt]===Pc,bb=e=>!!e&&typeof e=="object"&&e[Tt]===rp,kb=e=>!!e&&typeof e=="object"&&e[Tt]===Ja,Sb=e=>!!e&&typeof e=="object"&&e[Tt]===ip,np=e=>!!e&&typeof e=="object"&&e[Tt]===Rc,Eb=e=>!!e&&typeof e=="object"&&e[Tt]===Ga;function ap(e){if(e&&typeof e=="object")switch(e[Tt]){case Ja:case Ga:return!0}return!1}function Cb(e){if(e&&typeof e=="object")switch(e[Tt]){case Pc:case Ja:case Rc:case Ga:return!0}return!1}var xb=e=>(np(e)||ap(e))&&!!e.anchor;we.ALIAS=Pc;we.DOC=rp;we.MAP=Ja;we.NODE_TYPE=Tt;we.PAIR=ip;we.SCALAR=Rc;we.SEQ=Ga;we.hasAnchor=xb;we.isAlias=Nb;we.isCollection=ap;we.isDocument=bb;we.isMap=kb;we.isNode=Cb;we.isPair=Sb;we.isScalar=np;we.isSeq=Eb});var gn=P(Ac=>{"use strict";var fe=q(),Pe=Symbol("break visit"),op=Symbol("skip children"),gt=Symbol("remove node");function Ua(e,t){let r=sp(t);fe.isDocument(e)?hi(null,e.contents,r,Object.freeze([e]))===gt&&(e.contents=null):hi(null,e,r,Object.freeze([]))}Ua.BREAK=Pe;Ua.SKIP=op;Ua.REMOVE=gt;function hi(e,t,r,i){let n=cp(e,t,r,i);if(fe.isNode(n)||fe.isPair(n))return lp(e,i,n),hi(e,n,r,i);if(typeof n!="symbol"){if(fe.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=hi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Pe)return Pe;o===gt&&(t.items.splice(a,1),a-=1)}}}else if(fe.isPair(t)){i=Object.freeze(i.concat(t));let a=hi("key",t.key,r,i);if(a===Pe)return Pe;a===gt&&(t.key=null);let o=hi("value",t.value,r,i);if(o===Pe)return Pe;o===gt&&(t.value=null)}}return n}async function Ka(e,t){let r=sp(t);fe.isDocument(e)?await mi(null,e.contents,r,Object.freeze([e]))===gt&&(e.contents=null):await mi(null,e,r,Object.freeze([]))}Ka.BREAK=Pe;Ka.SKIP=op;Ka.REMOVE=gt;async function mi(e,t,r,i){let n=await cp(e,t,r,i);if(fe.isNode(n)||fe.isPair(n))return lp(e,i,n),mi(e,n,r,i);if(typeof n!="symbol"){if(fe.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await mi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Pe)return Pe;o===gt&&(t.items.splice(a,1),a-=1)}}}else if(fe.isPair(t)){i=Object.freeze(i.concat(t));let a=await mi("key",t.key,r,i);if(a===Pe)return Pe;a===gt&&(t.key=null);let o=await mi("value",t.value,r,i);if(o===Pe)return Pe;o===gt&&(t.value=null)}}return n}function sp(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 cp(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(fe.isMap(t))return r.Map?.(e,t,i);if(fe.isSeq(t))return r.Seq?.(e,t,i);if(fe.isPair(t))return r.Pair?.(e,t,i);if(fe.isScalar(t))return r.Scalar?.(e,t,i);if(fe.isAlias(t))return r.Alias?.(e,t,i)}function lp(e,t,r){let i=t[t.length-1];if(fe.isCollection(i))i.items[e]=r;else if(fe.isPair(i))e==="key"?i.key=r:i.value=r;else if(fe.isDocument(i))i.contents=r;else{let n=fe.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ac.visit=Ua;Ac.visitAsync=Ka});var _c=P(dp=>{"use strict";var up=q(),Pb=gn(),Rb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ab=e=>e.replace(/[!,[\]{}]/g,t=>Rb[t]),wn=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+Ab(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&&up.isNode(t.contents)){let a={};Pb.visit(t.contents,(o,s)=>{up.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(`
6
- `)}};wn.defaultYaml={explicit:!1,version:"1.2"};wn.defaultTags={"!!":"tag:yaml.org,2002:"};dp.Directives=wn});var Ya=P(yn=>{"use strict";var fp=q(),_b=gn();function Ib(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 pp(e){let t=new Set;return _b.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function hp(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Tb(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=pp(e));let o=hp(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(fp.isScalar(o.node)||fp.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}}yn.anchorIsValid=Ib;yn.anchorNames=pp;yn.createNodeAnchors=Tb;yn.findNewAnchor=hp});var Ic=P(mp=>{"use strict";function Nn(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=Nn(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=Nn(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=Nn(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=Nn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}mp.applyReviver=Nn});var tr=P(gp=>{"use strict";var jb=q();function vp(e,t,r){if(Array.isArray(e))return e.map((i,n)=>vp(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!jb.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}gp.toJS=vp});var Xa=P(yp=>{"use strict";var $b=Ic(),wp=q(),Ob=tr(),Tc=class{constructor(t){Object.defineProperty(this,wp.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(!wp.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=Ob.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?$b.applyReviver(a,{"":s},"",s):s}};yp.NodeBase=Tc});var bn=P(Np=>{"use strict";var Hb=Ya(),Db=gn(),vi=q(),Bb=Xa(),Lb=tr(),jc=class extends Bb.NodeBase{constructor(t){super(vi.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=[],Db.visit(t,{Node:(a,o)=>{(vi.isAlias(o)||vi.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||(Lb.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=Qa(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(Hb.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 Qa(e,t,r){if(vi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(vi.isCollection(t)){let i=0;for(let n of t.items){let a=Qa(e,n,r);a>i&&(i=a)}return i}else if(vi.isPair(t)){let i=Qa(e,t.key,r),n=Qa(e,t.value,r);return Math.max(i,n)}return 1}Np.Alias=jc});var oe=P($c=>{"use strict";var Vb=q(),Fb=Xa(),qb=tr(),Mb=e=>!e||typeof e!="function"&&typeof e!="object",rr=class extends Fb.NodeBase{constructor(t){super(Vb.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:qb.toJS(this.value,t,r)}toString(){return String(this.value)}};rr.BLOCK_FOLDED="BLOCK_FOLDED";rr.BLOCK_LITERAL="BLOCK_LITERAL";rr.PLAIN="PLAIN";rr.QUOTE_DOUBLE="QUOTE_DOUBLE";rr.QUOTE_SINGLE="QUOTE_SINGLE";$c.Scalar=rr;$c.isScalarValue=Mb});var kn=P(kp=>{"use strict";var Wb=bn(),Vr=q(),bp=oe(),zb="tag:yaml.org,2002:";function Jb(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 Gb(e,t,r){if(Vr.isDocument(e)&&(e=e.contents),Vr.isNode(e))return e;if(Vr.isPair(e)){let d=r.schema[Vr.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 Wb.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=zb+t.slice(2));let l=Jb(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new bp.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Vr.MAP]:Symbol.iterator in Object(e)?o[Vr.SEQ]:o[Vr.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 bp.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}kp.createNode=Gb});var eo=P(Za=>{"use strict";var Ub=kn(),wt=q(),Kb=Xa();function Oc(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 Ub.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 Sp=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Hc=class extends Kb.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>wt.isNode(i)||wt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Sp(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(wt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Oc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(wt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&wt.isScalar(a)?a.value:a:wt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!wt.isPair(r))return!1;let i=r.value;return i==null||t&&wt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return wt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(wt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Oc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Za.Collection=Hc;Za.collectionFromPath=Oc;Za.isEmptyPath=Sp});var Sn=P(to=>{"use strict";var Yb=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Dc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Xb=(e,t,r)=>e.endsWith(`
4
+ var lb=Object.create;var Cc=Object.defineProperty;var ub=Object.getOwnPropertyDescriptor;var db=Object.getOwnPropertyNames;var fb=Object.getPrototypeOf,pb=Object.prototype.hasOwnProperty;var za=(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 A=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ep=(e,t)=>{for(var r in t)Cc(e,r,{get:t[r],enumerable:!0})},hb=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of db(t))!pb.call(e,n)&&n!==r&&Cc(e,n,{get:()=>t[n],enumerable:!(i=ub(t,n))||i.enumerable});return e};var fi=(e,t,r)=>(r=e!=null?lb(fb(e)):{},hb(t||!e||!e.__esModule?Cc(r,"default",{value:e,enumerable:!0}):r,e));import{execFileSync as mb}from"child_process";import mn from"path";function pi(e,t){return mb("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function vb(e,t){let r=mn.normalize(e),i=mn.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Ee(e){try{let t=mn.resolve(pi(e,["rev-parse","--show-toplevel"])),i=pi(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?mn.resolve(i.slice(9)):t,a=null;try{a=pi(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!vb(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function tp(e){try{pi(e,["rev-parse","--is-inside-work-tree"]);let t=pi(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:mn.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 er(e){return tp(e).map(t=>t.root)}function Lr(e,t){try{let r=pi(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 gt=A(()=>{"use strict"});import{createHash as gb}from"crypto";function et(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function wb(e,t){t.has(e)&&et("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)||et("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&et("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),`[${e.map(i=>xc(i,t)).join(",")}]`}finally{t.delete(e)}}function yb(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&et("only plain objects are supported"),t.has(e)&&et("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&et("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))&&et("accessor properties are not supported"),`${JSON.stringify(o)}:${xc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function xc(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)||et("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?wb(e,t):yb(e,t);case"bigint":case"function":case"symbol":case"undefined":return et(`${typeof e} values are not supported`)}return et("unsupported value type")}function vn(e){return xc(e,new Set)}function j(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 gb("sha256").update(`${e}
5
+ ${vn(t)}`).digest("hex")}var pe=A(()=>{"use strict"});var q=P(we=>{"use strict";var Pc=Symbol.for("yaml.alias"),rp=Symbol.for("yaml.document"),Ja=Symbol.for("yaml.map"),ip=Symbol.for("yaml.pair"),Rc=Symbol.for("yaml.scalar"),Ga=Symbol.for("yaml.seq"),jt=Symbol.for("yaml.node.type"),Nb=e=>!!e&&typeof e=="object"&&e[jt]===Pc,bb=e=>!!e&&typeof e=="object"&&e[jt]===rp,kb=e=>!!e&&typeof e=="object"&&e[jt]===Ja,Sb=e=>!!e&&typeof e=="object"&&e[jt]===ip,np=e=>!!e&&typeof e=="object"&&e[jt]===Rc,Eb=e=>!!e&&typeof e=="object"&&e[jt]===Ga;function ap(e){if(e&&typeof e=="object")switch(e[jt]){case Ja:case Ga:return!0}return!1}function Cb(e){if(e&&typeof e=="object")switch(e[jt]){case Pc:case Ja:case Rc:case Ga:return!0}return!1}var xb=e=>(np(e)||ap(e))&&!!e.anchor;we.ALIAS=Pc;we.DOC=rp;we.MAP=Ja;we.NODE_TYPE=jt;we.PAIR=ip;we.SCALAR=Rc;we.SEQ=Ga;we.hasAnchor=xb;we.isAlias=Nb;we.isCollection=ap;we.isDocument=bb;we.isMap=kb;we.isNode=Cb;we.isPair=Sb;we.isScalar=np;we.isSeq=Eb});var gn=P(Ac=>{"use strict";var fe=q(),Pe=Symbol("break visit"),op=Symbol("skip children"),wt=Symbol("remove node");function Ua(e,t){let r=sp(t);fe.isDocument(e)?hi(null,e.contents,r,Object.freeze([e]))===wt&&(e.contents=null):hi(null,e,r,Object.freeze([]))}Ua.BREAK=Pe;Ua.SKIP=op;Ua.REMOVE=wt;function hi(e,t,r,i){let n=cp(e,t,r,i);if(fe.isNode(n)||fe.isPair(n))return lp(e,i,n),hi(e,n,r,i);if(typeof n!="symbol"){if(fe.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=hi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Pe)return Pe;o===wt&&(t.items.splice(a,1),a-=1)}}}else if(fe.isPair(t)){i=Object.freeze(i.concat(t));let a=hi("key",t.key,r,i);if(a===Pe)return Pe;a===wt&&(t.key=null);let o=hi("value",t.value,r,i);if(o===Pe)return Pe;o===wt&&(t.value=null)}}return n}async function Ka(e,t){let r=sp(t);fe.isDocument(e)?await mi(null,e.contents,r,Object.freeze([e]))===wt&&(e.contents=null):await mi(null,e,r,Object.freeze([]))}Ka.BREAK=Pe;Ka.SKIP=op;Ka.REMOVE=wt;async function mi(e,t,r,i){let n=await cp(e,t,r,i);if(fe.isNode(n)||fe.isPair(n))return lp(e,i,n),mi(e,n,r,i);if(typeof n!="symbol"){if(fe.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await mi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Pe)return Pe;o===wt&&(t.items.splice(a,1),a-=1)}}}else if(fe.isPair(t)){i=Object.freeze(i.concat(t));let a=await mi("key",t.key,r,i);if(a===Pe)return Pe;a===wt&&(t.key=null);let o=await mi("value",t.value,r,i);if(o===Pe)return Pe;o===wt&&(t.value=null)}}return n}function sp(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 cp(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(fe.isMap(t))return r.Map?.(e,t,i);if(fe.isSeq(t))return r.Seq?.(e,t,i);if(fe.isPair(t))return r.Pair?.(e,t,i);if(fe.isScalar(t))return r.Scalar?.(e,t,i);if(fe.isAlias(t))return r.Alias?.(e,t,i)}function lp(e,t,r){let i=t[t.length-1];if(fe.isCollection(i))i.items[e]=r;else if(fe.isPair(i))e==="key"?i.key=r:i.value=r;else if(fe.isDocument(i))i.contents=r;else{let n=fe.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ac.visit=Ua;Ac.visitAsync=Ka});var _c=P(dp=>{"use strict";var up=q(),Pb=gn(),Rb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ab=e=>e.replace(/[!,[\]{}]/g,t=>Rb[t]),wn=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+Ab(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&&up.isNode(t.contents)){let a={};Pb.visit(t.contents,(o,s)=>{up.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(`
6
+ `)}};wn.defaultYaml={explicit:!1,version:"1.2"};wn.defaultTags={"!!":"tag:yaml.org,2002:"};dp.Directives=wn});var Ya=P(yn=>{"use strict";var fp=q(),_b=gn();function Ib(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 pp(e){let t=new Set;return _b.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function hp(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Tb(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=pp(e));let o=hp(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(fp.isScalar(o.node)||fp.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}}yn.anchorIsValid=Ib;yn.anchorNames=pp;yn.createNodeAnchors=Tb;yn.findNewAnchor=hp});var Ic=P(mp=>{"use strict";function Nn(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=Nn(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=Nn(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=Nn(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=Nn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}mp.applyReviver=Nn});var tr=P(gp=>{"use strict";var jb=q();function vp(e,t,r){if(Array.isArray(e))return e.map((i,n)=>vp(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!jb.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}gp.toJS=vp});var Xa=P(yp=>{"use strict";var $b=Ic(),wp=q(),Ob=tr(),Tc=class{constructor(t){Object.defineProperty(this,wp.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(!wp.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=Ob.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?$b.applyReviver(a,{"":s},"",s):s}};yp.NodeBase=Tc});var bn=P(Np=>{"use strict";var Hb=Ya(),Db=gn(),vi=q(),Bb=Xa(),Lb=tr(),jc=class extends Bb.NodeBase{constructor(t){super(vi.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=[],Db.visit(t,{Node:(a,o)=>{(vi.isAlias(o)||vi.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||(Lb.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=Qa(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(Hb.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 Qa(e,t,r){if(vi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(vi.isCollection(t)){let i=0;for(let n of t.items){let a=Qa(e,n,r);a>i&&(i=a)}return i}else if(vi.isPair(t)){let i=Qa(e,t.key,r),n=Qa(e,t.value,r);return Math.max(i,n)}return 1}Np.Alias=jc});var oe=P($c=>{"use strict";var Vb=q(),Fb=Xa(),qb=tr(),Mb=e=>!e||typeof e!="function"&&typeof e!="object",rr=class extends Fb.NodeBase{constructor(t){super(Vb.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:qb.toJS(this.value,t,r)}toString(){return String(this.value)}};rr.BLOCK_FOLDED="BLOCK_FOLDED";rr.BLOCK_LITERAL="BLOCK_LITERAL";rr.PLAIN="PLAIN";rr.QUOTE_DOUBLE="QUOTE_DOUBLE";rr.QUOTE_SINGLE="QUOTE_SINGLE";$c.Scalar=rr;$c.isScalarValue=Mb});var kn=P(kp=>{"use strict";var Wb=bn(),Vr=q(),bp=oe(),zb="tag:yaml.org,2002:";function Jb(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 Gb(e,t,r){if(Vr.isDocument(e)&&(e=e.contents),Vr.isNode(e))return e;if(Vr.isPair(e)){let d=r.schema[Vr.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 Wb.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=zb+t.slice(2));let l=Jb(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new bp.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Vr.MAP]:Symbol.iterator in Object(e)?o[Vr.SEQ]:o[Vr.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 bp.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}kp.createNode=Gb});var eo=P(Za=>{"use strict";var Ub=kn(),yt=q(),Kb=Xa();function Oc(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 Ub.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 Sp=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Hc=class extends Kb.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>yt.isNode(i)||yt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Sp(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(yt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Oc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(yt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&yt.isScalar(a)?a.value:a:yt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!yt.isPair(r))return!1;let i=r.value;return i==null||t&&yt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return yt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(yt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Oc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Za.Collection=Hc;Za.collectionFromPath=Oc;Za.isEmptyPath=Sp});var Sn=P(to=>{"use strict";var Yb=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Dc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Xb=(e,t,r)=>e.endsWith(`
7
7
  `)?Dc(r,t):r.includes(`
8
8
  `)?`
9
9
  `+Dc(r,t):(e.endsWith(" ")?"":" ")+r;to.indentComment=Dc;to.lineComment=Xb;to.stringifyComment=Yb});var Cp=P(En=>{"use strict";var Qb="flow",Bc="block",ro="quoted";function Zb(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,g=-1;r===Bc&&(h=Ep(e,h,t.length),h!==-1&&(d=h+c));for(let S;S=e[h+=1];){if(r===ro&&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}g=h}if(S===`
@@ -12,7 +12,7 @@ ${vn(t)}`).digest("hex")}var pe=A(()=>{"use strict"});var q=P(we=>{"use strict";
12
12
  `&&w!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===ro){for(;p===" "||p===" ";)p=S,S=e[h+=1],v=!0;let w=h>g+1?h-2:m-1;if(u[w])return e;l.push(w),u[w]=!0,d=w+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 w=l[S],E=l[S+1]||e.length;w===0?b=`
13
13
  ${t}${e.slice(0,E)}`:(r===ro&&u[w]&&(b+=`${e[w]}\\`),b+=`
14
14
  ${t}${e.slice(w+1,E)}`)}return b}function Ep(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!==`
15
- `);i=t,n=t+1,a=e[n]}return i}En.FOLD_BLOCK=Bc;En.FOLD_FLOW=Qb;En.FOLD_QUOTED=ro;En.foldFlowLines=Zb});var xn=P(xp=>{"use strict";var et=oe(),ir=Cp(),no=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ao=e=>/^(%|---|\.\.\.)/m.test(e);function ek(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
+ `);i=t,n=t+1,a=e[n]}return i}En.FOLD_BLOCK=Bc;En.FOLD_FLOW=Qb;En.FOLD_QUOTED=ro;En.foldFlowLines=Zb});var xn=P(xp=>{"use strict";var tt=oe(),ir=Cp(),no=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ao=e=>/^(%|---|\.\.\.)/m.test(e);function ek(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]===`
16
16
  `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Cn(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ao(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)+`
17
17
 
18
18
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
@@ -21,28 +21,28 @@ ${t}${e.slice(w+1,E)}`)}return b}function Ep(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
21
21
  ${r}`)+"'";return t.implicitKey?i:ir.foldFlowLines(i,r,ir.FOLD_FLOW,no(t,!1))}function gi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Cn;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Lc:a&&!n?i=Cn:i=r?Lc:Cn}return i(e,t)}var Vc;try{Vc=new RegExp(`(^|(?<!
22
22
  ))
23
23
  +(?!
24
- |$)`,"g")}catch{Vc=/\n+(?!\n|$)/g}function io({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 gi(r,i);let l=i.indent||(i.forceBlockIndent||ao(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===et.Scalar.BLOCK_FOLDED?!1:t===et.Scalar.BLOCK_LITERAL?!0:!ek(r,c,l.length);if(!r)return u?`|
24
+ |$)`,"g")}catch{Vc=/\n+(?!\n|$)/g}function io({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 gi(r,i);let l=i.indent||(i.forceBlockIndent||ao(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===tt.Scalar.BLOCK_FOLDED?!1:t===tt.Scalar.BLOCK_LITERAL?!0:!ek(r,c,l.length);if(!r)return u?`|
25
25
  `:`>
26
26
  `;let d,f;for(f=r.length;f>0;--f){let E=r[f-1];if(E!==`
27
27
  `&&E!==" "&&E!==" ")break}let p=r.substring(f),v=p.indexOf(`
28
28
  `);v===-1?d="-":r===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
29
29
  `&&(p=p.slice(0,-1)),p=p.replace(Vc,`$&${l}`));let h=!1,m,g=-1;for(m=0;m<r.length;++m){let E=r[m];if(E===" ")h=!0;else if(E===`
30
30
  `)g=m;else break}let b=r.substring(0,g<m?g+1:m);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let w=(h?l?"2":"1":"")+d;if(e&&(w+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
31
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),k=!1,x=no(i,!0);o!=="folded"&&t!==et.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{k=!0});let N=ir.foldFlowLines(`${b}${E}${p}`,l,ir.FOLD_BLOCK,x);if(!k)return`>${w}
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),k=!1,x=no(i,!0);o!=="folded"&&t!==tt.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{k=!0});let N=ir.foldFlowLines(`${b}${E}${p}`,l,ir.FOLD_BLOCK,x);if(!k)return`>${w}
32
32
  ${l}${N}`}return r=r.replace(/\n+/g,`$&${l}`),`|${w}
33
33
  ${l}${b}${r}${p}`}function tk(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(`
34
34
  `)||u&&/[[\]{},]/.test(a))return gi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
- `)?gi(a,t):io(e,t,r,i);if(!s&&!u&&n!==et.Scalar.PLAIN&&a.includes(`
35
+ `)?gi(a,t):io(e,t,r,i);if(!s&&!u&&n!==tt.Scalar.PLAIN&&a.includes(`
36
36
  `))return io(e,t,r,i);if(ao(a)){if(c==="")return t.forceBlockIndent=!0,io(e,t,r,i);if(s&&c===l)return gi(a,t)}let d=a.replace(/\n+/g,`$&
37
- ${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 gi(a,t)}return s?d:ir.foldFlowLines(d,c,ir.FOLD_FLOW,no(t,!1))}function rk(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==et.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=et.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case et.Scalar.BLOCK_FOLDED:case et.Scalar.BLOCK_LITERAL:return n||a?gi(o.value,t):io(o,t,r,i);case et.Scalar.QUOTE_DOUBLE:return Cn(o.value,t);case et.Scalar.QUOTE_SINGLE:return Lc(o.value,t);case et.Scalar.PLAIN:return tk(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}xp.stringifyString=rk});var Pn=P(Fc=>{"use strict";var ik=Ya(),nr=q(),nk=Sn(),ak=xn();function ok(e,t){let r=Object.assign({blockQuote:!0,commentString:nk.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 sk(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(nr.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 ck(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(nr.isScalar(e)||nr.isCollection(e))&&e.anchor;a&&ik.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 lk(e,t,r,i){if(nr.isPair(e))return e.toString(t,r,i);if(nr.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=nr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=sk(t.doc.schema.tags,a));let o=ck(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):nr.isScalar(a)?ak.stringifyString(a,t,r,i):a.toString(t,r,i);return o?nr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
- ${t.indent}${s}`:s}Fc.createStringifyContext=ok;Fc.stringify=lk});var _p=P(Ap=>{"use strict";var jt=q(),Pp=oe(),Rp=Pn(),Rn=Sn();function uk({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=jt.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(jt.isCollection(e)||!jt.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||jt.isCollection(e)||(jt.isScalar(e)?e.type===Pp.Scalar.BLOCK_FOLDED||e.type===Pp.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=Rp.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+=Rn.lineComment(m,r.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Rn.lineComment(m,r.indent,l(f))),m=`? ${m}
39
- ${s}:`):(m=`${m}:`,f&&(m+=Rn.lineComment(m,r.indent,l(f))));let g,b,S;jt.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,S=t.comment):(g=!1,b=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&jt.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&jt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let w=!1,E=Rp.stringify(t,r,()=>w=!0,()=>h=!0),k=" ";if(f||g||b){if(k=g?`
37
+ ${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 gi(a,t)}return s?d:ir.foldFlowLines(d,c,ir.FOLD_FLOW,no(t,!1))}function rk(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==tt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=tt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case tt.Scalar.BLOCK_FOLDED:case tt.Scalar.BLOCK_LITERAL:return n||a?gi(o.value,t):io(o,t,r,i);case tt.Scalar.QUOTE_DOUBLE:return Cn(o.value,t);case tt.Scalar.QUOTE_SINGLE:return Lc(o.value,t);case tt.Scalar.PLAIN:return tk(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}xp.stringifyString=rk});var Pn=P(Fc=>{"use strict";var ik=Ya(),nr=q(),nk=Sn(),ak=xn();function ok(e,t){let r=Object.assign({blockQuote:!0,commentString:nk.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 sk(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(nr.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 ck(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(nr.isScalar(e)||nr.isCollection(e))&&e.anchor;a&&ik.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 lk(e,t,r,i){if(nr.isPair(e))return e.toString(t,r,i);if(nr.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=nr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=sk(t.doc.schema.tags,a));let o=ck(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):nr.isScalar(a)?ak.stringifyString(a,t,r,i):a.toString(t,r,i);return o?nr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
+ ${t.indent}${s}`:s}Fc.createStringifyContext=ok;Fc.stringify=lk});var _p=P(Ap=>{"use strict";var $t=q(),Pp=oe(),Rp=Pn(),Rn=Sn();function uk({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=$t.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if($t.isCollection(e)||!$t.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||$t.isCollection(e)||($t.isScalar(e)?e.type===Pp.Scalar.BLOCK_FOLDED||e.type===Pp.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=Rp.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+=Rn.lineComment(m,r.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=Rn.lineComment(m,r.indent,l(f))),m=`? ${m}
39
+ ${s}:`):(m=`${m}:`,f&&(m+=Rn.lineComment(m,r.indent,l(f))));let g,b,S;$t.isNode(t)?(g=!!t.spaceBefore,b=t.commentBefore,S=t.comment):(g=!1,b=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&$t.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&$t.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let w=!1,E=Rp.stringify(t,r,()=>w=!0,()=>h=!0),k=" ";if(f||g||b){if(k=g?`
40
40
  `:"",b){let x=l(b);k+=`
41
41
  ${Rn.indentComment(x,r.indent)}`}E===""&&!r.inFlow?k===`
42
42
  `&&S&&(k=`
43
43
 
44
44
  `):k+=`
45
- ${r.indent}`}else if(!p&&jt.isCollection(t)){let x=E[0],N=E.indexOf(`
45
+ ${r.indent}`}else if(!p&&$t.isCollection(t)){let x=E[0],N=E.indexOf(`
46
46
  `),y=N!==-1,C=r.inFlow??t.flow??t.items.length===0;if(y||!C){let O=!1;if(y&&(x==="&"||x==="!")){let $=E.indexOf(" ");x==="&"&&$!==-1&&$<N&&E[$+1]==="!"&&($=E.indexOf(" ",$+1)),($===-1||N<$)&&(O=!0)}O||(k=`
47
47
  ${r.indent}`)}}else(E===""||E[0]===`
48
48
  `)&&(k="");return m+=k+E,r.inFlow?w&&i&&i():S&&!w?m+=Rn.lineComment(m,r.indent,l(S)):h&&n&&n(),m}Ap.stringifyPair=uk});var Mc=P(qc=>{"use strict";var Ip=za("process");function dk(e,...t){e==="debug"&&console.log(...t)}function fk(e,t){(e==="debug"||e==="warn")&&(typeof Ip.emitWarning=="function"?Ip.emitWarning(t):console.warn(t))}qc.debug=dk;qc.warn=fk});var uo=P(lo=>{"use strict";var co=q(),Tp=oe(),oo="<<",so={identify:e=>e===oo||typeof e=="symbol"&&e.description===oo,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Tp.Scalar(Symbol(oo)),{addToJSMap:jp}),stringify:()=>oo},pk=(e,t)=>(so.identify(t)||co.isScalar(t)&&(!t.type||t.type===Tp.Scalar.PLAIN)&&so.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===so.tag&&r.default);function jp(e,t,r){let i=$p(e,r);if(co.isSeq(i))for(let n of i.items)Wc(e,t,n);else if(Array.isArray(i))for(let n of i)Wc(e,t,n);else Wc(e,t,i)}function Wc(e,t,r){let i=$p(e,r);if(!co.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 $p(e,t){return e&&co.isAlias(t)?t.resolve(e.doc,e):t}lo.addMergeToJSMap=jp;lo.isMergeKey=pk;lo.merge=so});var Jc=P(Dp=>{"use strict";var hk=Mc(),Op=uo(),mk=Pn(),Hp=q(),zc=tr();function vk(e,t,{key:r,value:i}){if(Hp.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Op.isMergeKey(e,r))Op.addMergeToJSMap(e,t,i);else{let n=zc.toJS(r,"",e);if(t instanceof Map)t.set(n,zc.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=gk(r,n,e),o=zc.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 gk(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Hp.isNode(e)&&r?.doc){let i=mk.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)+'..."'),hk.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)}Dp.addPairToJSMap=vk});var ar=P(Gc=>{"use strict";var Bp=kn(),wk=_p(),yk=Jc(),fo=q();function Nk(e,t,r){let i=Bp.createNode(e,void 0,r),n=Bp.createNode(t,void 0,r);return new po(i,n)}var po=class e{constructor(t,r=null){Object.defineProperty(this,fo.NODE_TYPE,{value:fo.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return fo.isNode(r)&&(r=r.clone(t)),fo.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return yk.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?wk.stringifyPair(this,t,r,i):JSON.stringify(this)}};Gc.Pair=po;Gc.createPair=Nk});var Uc=P(Vp=>{"use strict";var Fr=q(),Lp=Pn(),ho=Sn();function bk(e,t,r){return(t.inFlow??e.flow?Sk:kk)(e,t,r)}function kk({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(Fr.isNode(h))!d&&h.spaceBefore&&f.push(""),mo(r,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(Fr.isPair(h)){let b=Fr.isNode(h.key)?h.key:null;b&&(!d&&b.spaceBefore&&f.push(""),mo(r,f,b.commentBefore,d))}d=!1;let g=Lp.stringify(h,u,()=>m=null,()=>d=!0);m&&(g+=ho.lineComment(g,a,l(m))),d&&m&&(d=!1),f.push(i+g)}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?`
@@ -117,64 +117,64 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
117
117
  `});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 km(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 Jl(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:`
118
118
  `};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})}}}Do.createScalarToken=pC;Do.resolveAsScalar=fC;Do.setScalarValue=hC});var Cm=P(Em=>{"use strict";var vC=e=>"type"in e?Lo(e):Bo(e);function Lo(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Lo(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Bo(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Bo(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Bo(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 Bo({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Lo(t)),r)for(let a of r)n+=a.source;return i&&(n+=Lo(i)),n}Em.stringify=vC});var Am=P(Rm=>{"use strict";var Gl=Symbol("break visit"),gC=Symbol("skip children"),xm=Symbol("remove item");function zr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Pm(Object.freeze([]),e,t)}zr.BREAK=Gl;zr.SKIP=gC;zr.REMOVE=xm;zr.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};zr.parentCollection=(e,t)=>{let r=zr.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 Pm(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=Pm(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Gl)return Gl;s===xm&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Rm.visit=zr});var Vo=P(Re=>{"use strict";var Ul=Sm(),wC=Cm(),yC=Am(),Kl="\uFEFF",Yl="",Xl="",Ql="",NC=e=>!!e&&"items"in e,bC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function kC(e){switch(e){case Kl:return"<BOM>";case Yl:return"<DOC>";case Xl:return"<FLOW_END>";case Ql:return"<SCALAR>";default:return JSON.stringify(e)}}function SC(e){switch(e){case Kl:return"byte-order-mark";case Yl:return"doc-mode";case Xl:return"flow-error-end";case Ql:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
119
119
  `:case`\r
120
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Re.createScalarToken=Ul.createScalarToken;Re.resolveAsScalar=Ul.resolveAsScalar;Re.setScalarValue=Ul.setScalarValue;Re.stringify=wC.stringify;Re.visit=yC.visit;Re.BOM=Kl;Re.DOCUMENT=Yl;Re.FLOW_END=Xl;Re.SCALAR=Ql;Re.isCollection=NC;Re.isScalar=bC;Re.prettyToken=kC;Re.tokenType=SC});var tu=P(Im=>{"use strict";var Wn=Vo();function tt(e){switch(e){case void 0:case" ":case`
120
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Re.createScalarToken=Ul.createScalarToken;Re.resolveAsScalar=Ul.resolveAsScalar;Re.setScalarValue=Ul.setScalarValue;Re.stringify=wC.stringify;Re.visit=yC.visit;Re.BOM=Kl;Re.DOCUMENT=Yl;Re.FLOW_END=Xl;Re.SCALAR=Ql;Re.isCollection=NC;Re.isScalar=bC;Re.prettyToken=kC;Re.tokenType=SC});var tu=P(Im=>{"use strict";var Wn=Vo();function rt(e){switch(e){case void 0:case" ":case`
121
121
  `:case"\r":case" ":return!0;default:return!1}}var _m=new Set("0123456789ABCDEFabcdef"),EC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fo=new Set(",[]{}"),CC=new Set(` ,[]{}
122
122
  \r `),Zl=e=>!e||CC.has(e),eu=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===`
123
123
  `?!0:r==="\r"?this.buffer[t+1]===`
124
124
  `:!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===`
125
125
  `||!n&&!this.atEnd)return t+i+1}return r===`
126
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&tt(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Wn.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 Wn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&tt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!tt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&tt(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Zl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&tt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Wn.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(Zl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||tt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
126
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&rt(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Wn.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 Wn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&rt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!rt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&rt(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Zl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&rt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Wn.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(Zl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||rt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
128
128
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
129
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>tt(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
+ `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>rt(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
130
130
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
131
131
  `)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(`
132
132
  `,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===`
133
133
  `;)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===`
134
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Wn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(tt(a)||t&&Fo.has(a))break;r=i}else if(tt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Wn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(rt(a)||t&&Fo.has(a))break;r=i}else if(rt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
135
135
  `?(i+=1,n=`
136
136
  `,a=this.buffer[i+1]):r=i),a==="#"||t&&Fo.has(a))break;if(n===`
137
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Fo.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Wn.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(Zl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(tt(i)||r&&Fo.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!tt(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(EC.has(r))r=this.buffer[++t];else if(r==="%"&&_m.has(this.buffer[t+1])&&_m.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
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Fo.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Wn.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(Zl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(rt(i)||r&&Fo.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!rt(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(EC.has(r))r=this.buffer[++t];else if(r==="%"&&_m.has(this.buffer[t+1])&&_m.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
138
138
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
139
139
  `?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)}};Im.Lexer=eu});var iu=P(Tm=>{"use strict";var ru=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}}}};Tm.LineCounter=ru});var au=P(Dm=>{"use strict";var xC=za("process"),jm=Vo(),PC=tu();function lr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function $m(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 Hm(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 qo(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 Ei(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 Mo(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 Om(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!lr(t.start,"explicit-key-ind")&&!lr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Hm(t.value)?t.value.end?Mo(t.value.end,t.sep):t.value.end=t.sep:Mo(t.start,t.sep),delete t.sep)}var nu=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 PC.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,xC.env.LOG_TOKENS&&console.log("|",jm.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=jm.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"&&Om(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&&$m(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":{$m(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=qo(this.peek(2)),i=Ei(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(`
140
140
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
141
141
  `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Mo(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(lr(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Hm(r.key)&&!lr(r.sep,"newline")){let o=Ei(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(lr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ei(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):lr(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!lr(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Mo(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||lr(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=qo(i),a=Ei(n);Om(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
142
142
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
143
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=qo(t),i=Ei(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=qo(t),i=Ei(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())}}};Dm.Parser=nu});var qm=P(Jn=>{"use strict";var Bm=zl(),RC=Dn(),zn=Vn(),AC=Mc(),_C=q(),IC=iu(),Lm=au();function Vm(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new IC.LineCounter||null,prettyErrors:t}}function TC(e,t={}){let{lineCounter:r,prettyErrors:i}=Vm(t),n=new Lm.Parser(r?.addNewLine),a=new Bm.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(zn.prettifyError(e,r)),s.warnings.forEach(zn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Fm(e,t={}){let{lineCounter:r,prettyErrors:i}=Vm(t),n=new Lm.Parser(r?.addNewLine),a=new Bm.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 zn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(zn.prettifyError(e,r)),o.warnings.forEach(zn.prettifyError(e,r))),o}function jC(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Fm(e,r);if(!n)return null;if(n.warnings.forEach(a=>AC.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 $C(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 _C.isDocument(e)&&!i?e.toString(r):new RC.Document(e,i,r).toString(r)}Jn.parse=jC;Jn.parseAllDocuments=TC;Jn.parseDocument=Fm;Jn.stringify=$C});var Jr=P(J=>{"use strict";var OC=zl(),HC=Dn(),DC=Cl(),ou=Vn(),BC=bn(),ur=q(),LC=ar(),VC=oe(),FC=sr(),qC=cr(),MC=Vo(),WC=tu(),zC=iu(),JC=au(),Wo=qm(),Mm=gn();J.Composer=OC.Composer;J.Document=HC.Document;J.Schema=DC.Schema;J.YAMLError=ou.YAMLError;J.YAMLParseError=ou.YAMLParseError;J.YAMLWarning=ou.YAMLWarning;J.Alias=BC.Alias;J.isAlias=ur.isAlias;J.isCollection=ur.isCollection;J.isDocument=ur.isDocument;J.isMap=ur.isMap;J.isNode=ur.isNode;J.isPair=ur.isPair;J.isScalar=ur.isScalar;J.isSeq=ur.isSeq;J.Pair=LC.Pair;J.Scalar=VC.Scalar;J.YAMLMap=FC.YAMLMap;J.YAMLSeq=qC.YAMLSeq;J.CST=MC;J.Lexer=WC.Lexer;J.LineCounter=zC.LineCounter;J.Parser=JC.Parser;J.parse=Wo.parse;J.parseAllDocuments=Wo.parseAllDocuments;J.parseDocument=Wo.parseDocument;J.stringify=Wo.stringify;J.visit=Mm.visit;J.visitAsync=Mm.visitAsync});import su from"path";function KC(e){return e.toLowerCase().startsWith(".env")}function yt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>KC(i))?"environment-file":r.some(i=>UC.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>GC.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function cu(e,t){let r=yt(t);if(r)return r;let i=su.resolve(e.projectRoot,...t.split("/")),n=su.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===su.resolve(e.configFile)?"native-runtime":null}var GC,UC,Gn=A(()=>{"use strict";GC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),UC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function dr(e){return e!==0&&e!==0n&&e!=="0"}function Fe(e,t){return dr(e.dev)&&dr(t.dev)&&dr(e.ino)&&dr(t.ino)}function W(e,t){let r=dr(e.dev)&&dr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=dr(e.ino)&&dr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Un=A(()=>{"use strict"});var Nt=A(()=>{"use strict";Un()});import{createHash as YC}from"node:crypto";import{promises as rt}from"node:fs";import qe from"node:path";import{TextDecoder as XC}from"node:util";function lu(e,t){let r=qe.relative(e,t);return r===""||!qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qe.sep}`)}function QC(e){let t=qe.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})||qe.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=yt(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 ZC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ex(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Wm(e){let t=await rt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await rt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tx(e,t){let r=qe.resolve(e),i=qe.resolve(t);if(!lu(r,i))throw new Error("Native artifact path is outside its root");let n=[await Wm(r)],a=r;for(let o of qe.relative(r,i).split(qe.sep).filter(Boolean)){a=qe.join(a,o);let s=await Wm(a);if(!lu(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function zm(e){for(let t of e){let r=await rt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ex(t,r)||await rt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ae(e){let t=QC(e.ref),r=e.maxBytes===null?null:ZC(e.maxBytes??Kn),i=qe.resolve(e.root,...t.split("/")),n=await tx(e.root,qe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await rt.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 rt.realpath(i);if(!lu(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await rt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),rt.lstat(i),rt.realpath(i)]);if(await zm(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!zo(a,c)||!zo(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,w=await s.read(p,0,Math.min(p.length,S),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),rt.lstat(i),rt.realpath(i)]);if(await zm(n),!h.isFile()||h.isSymbolicLink()||m!==o||!zo(c,v)||!zo(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),b;try{b=new XC("utf-8",{fatal:!0}).decode(g)}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:YC("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var Kn,it=A(()=>{"use strict";Gn();Nt();Kn=1024*1024});import{randomUUID as rx}from"crypto";import{promises as he}from"fs";import nt from"path";function Jo(e,t){let r=nt.relative(e,t);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}function ix(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Go(e,t){return W({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function nx(e,t){return Go(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Jm(e){let t=await he.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 he.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ci(e){for(let t of e){let r=await he.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ix(t,r)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ax(e,t,r){let[i,n]=await Promise.all([he.lstat(e),he.realpath(e),r?Ci(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Go(i,t)||r&&!Jo(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function ox(e,t){let r=nt.resolve(e),i=nt.resolve(t);if(!Jo(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Jm(r)],a=nt.relative(r,i).split(nt.sep).filter(Boolean),o=r;for(let s of a){await Ci(n),o=nt.join(o,s);try{await he.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Jm(o);if(!Jo(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ci(n),n}async function sx(e){let t;try{t=await he.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 cx(e,t,r={}){let i=nt.dirname(e),n=r.containedRoot?await ox(r.containedRoot,i):null;n||await he.mkdir(i,{recursive:!0});let a=nt.join(i,`.${nt.basename(e)}.${rx()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await he.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([he.lstat(a),he.realpath(a)]);if(await Ci(n),!l.isFile()||l.isSymbolicLink()||!Go(s,l)||!Jo(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(),!Go(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 ax(a,c,n),await r.beforeCommit?.(),n){await Ci(n);let l=await he.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!nx(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await he.link(a,e),await he.unlink(a)):await he.rename(a,e),await sx(i)}catch(l){if(await o?.close(),!n)await he.rm(a,{force:!0});else try{await Ci(n),await he.rm(a,{force:!0})}catch{}throw l}}async function bt(e,t,r={}){await cx(e,t,r)}async function Me(e,t,r={}){await bt(e,JSON.stringify(t,null,2)+`
144
- `,r)}var se=A(()=>{"use strict";Nt()});function dx(e,t){return uu[e][t]}function Uo(e){return Gm.get(e.trim().toLocaleLowerCase("en-US"))??null}function Um(e){return du.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ko(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${dx(e,r)}
143
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=qo(t),i=Ei(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=qo(t),i=Ei(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())}}};Dm.Parser=nu});var qm=P(Jn=>{"use strict";var Bm=zl(),RC=Dn(),zn=Vn(),AC=Mc(),_C=q(),IC=iu(),Lm=au();function Vm(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new IC.LineCounter||null,prettyErrors:t}}function TC(e,t={}){let{lineCounter:r,prettyErrors:i}=Vm(t),n=new Lm.Parser(r?.addNewLine),a=new Bm.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(zn.prettifyError(e,r)),s.warnings.forEach(zn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Fm(e,t={}){let{lineCounter:r,prettyErrors:i}=Vm(t),n=new Lm.Parser(r?.addNewLine),a=new Bm.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 zn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(zn.prettifyError(e,r)),o.warnings.forEach(zn.prettifyError(e,r))),o}function jC(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Fm(e,r);if(!n)return null;if(n.warnings.forEach(a=>AC.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 $C(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 _C.isDocument(e)&&!i?e.toString(r):new RC.Document(e,i,r).toString(r)}Jn.parse=jC;Jn.parseAllDocuments=TC;Jn.parseDocument=Fm;Jn.stringify=$C});var Jr=P(J=>{"use strict";var OC=zl(),HC=Dn(),DC=Cl(),ou=Vn(),BC=bn(),ur=q(),LC=ar(),VC=oe(),FC=sr(),qC=cr(),MC=Vo(),WC=tu(),zC=iu(),JC=au(),Wo=qm(),Mm=gn();J.Composer=OC.Composer;J.Document=HC.Document;J.Schema=DC.Schema;J.YAMLError=ou.YAMLError;J.YAMLParseError=ou.YAMLParseError;J.YAMLWarning=ou.YAMLWarning;J.Alias=BC.Alias;J.isAlias=ur.isAlias;J.isCollection=ur.isCollection;J.isDocument=ur.isDocument;J.isMap=ur.isMap;J.isNode=ur.isNode;J.isPair=ur.isPair;J.isScalar=ur.isScalar;J.isSeq=ur.isSeq;J.Pair=LC.Pair;J.Scalar=VC.Scalar;J.YAMLMap=FC.YAMLMap;J.YAMLSeq=qC.YAMLSeq;J.CST=MC;J.Lexer=WC.Lexer;J.LineCounter=zC.LineCounter;J.Parser=JC.Parser;J.parse=Wo.parse;J.parseAllDocuments=Wo.parseAllDocuments;J.parseDocument=Wo.parseDocument;J.stringify=Wo.stringify;J.visit=Mm.visit;J.visitAsync=Mm.visitAsync});import su from"path";function KC(e){return e.toLowerCase().startsWith(".env")}function Nt(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>KC(i))?"environment-file":r.some(i=>UC.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>GC.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function cu(e,t){let r=Nt(t);if(r)return r;let i=su.resolve(e.projectRoot,...t.split("/")),n=su.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===su.resolve(e.configFile)?"native-runtime":null}var GC,UC,Gn=A(()=>{"use strict";GC=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),UC=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function dr(e){return e!==0&&e!==0n&&e!=="0"}function Fe(e,t){return dr(e.dev)&&dr(t.dev)&&dr(e.ino)&&dr(t.ino)}function W(e,t){let r=dr(e.dev)&&dr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=dr(e.ino)&&dr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Un=A(()=>{"use strict"});var bt=A(()=>{"use strict";Un()});import{createHash as YC}from"node:crypto";import{promises as it}from"node:fs";import qe from"node:path";import{TextDecoder as XC}from"node:util";function lu(e,t){let r=qe.relative(e,t);return r===""||!qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qe.sep}`)}function QC(e){let t=qe.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})||qe.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=Nt(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 ZC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ex(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Wm(e){let t=await it.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await it.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tx(e,t){let r=qe.resolve(e),i=qe.resolve(t);if(!lu(r,i))throw new Error("Native artifact path is outside its root");let n=[await Wm(r)],a=r;for(let o of qe.relative(r,i).split(qe.sep).filter(Boolean)){a=qe.join(a,o);let s=await Wm(a);if(!lu(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function zm(e){for(let t of e){let r=await it.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ex(t,r)||await it.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ae(e){let t=QC(e.ref),r=e.maxBytes===null?null:ZC(e.maxBytes??Kn),i=qe.resolve(e.root,...t.split("/")),n=await tx(e.root,qe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await it.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 it.realpath(i);if(!lu(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await it.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),it.lstat(i),it.realpath(i)]);if(await zm(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!zo(a,c)||!zo(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,w=await s.read(p,0,Math.min(p.length,S),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),it.lstat(i),it.realpath(i)]);if(await zm(n),!h.isFile()||h.isSymbolicLink()||m!==o||!zo(c,v)||!zo(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),b;try{b=new XC("utf-8",{fatal:!0}).decode(g)}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:YC("sha256").update(g).digest("hex"),text:b}}finally{await s.close()}}var Kn,nt=A(()=>{"use strict";Gn();bt();Kn=1024*1024});import{randomUUID as rx}from"crypto";import{promises as he}from"fs";import at from"path";function Jo(e,t){let r=at.relative(e,t);return r===""||!at.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${at.sep}`)}function ix(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Go(e,t){return W({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function nx(e,t){return Go(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Jm(e){let t=await he.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 he.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ci(e){for(let t of e){let r=await he.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ix(t,r)||await he.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ax(e,t,r){let[i,n]=await Promise.all([he.lstat(e),he.realpath(e),r?Ci(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Go(i,t)||r&&!Jo(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function ox(e,t){let r=at.resolve(e),i=at.resolve(t);if(!Jo(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Jm(r)],a=at.relative(r,i).split(at.sep).filter(Boolean),o=r;for(let s of a){await Ci(n),o=at.join(o,s);try{await he.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Jm(o);if(!Jo(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ci(n),n}async function sx(e){let t;try{t=await he.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 cx(e,t,r={}){let i=at.dirname(e),n=r.containedRoot?await ox(r.containedRoot,i):null;n||await he.mkdir(i,{recursive:!0});let a=at.join(i,`.${at.basename(e)}.${rx()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await he.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([he.lstat(a),he.realpath(a)]);if(await Ci(n),!l.isFile()||l.isSymbolicLink()||!Go(s,l)||!Jo(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(),!Go(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 ax(a,c,n),await r.beforeCommit?.(),n){await Ci(n);let l=await he.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!nx(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await he.link(a,e),await he.unlink(a)):await he.rename(a,e),await sx(i)}catch(l){if(await o?.close(),!n)await he.rm(a,{force:!0});else try{await Ci(n),await he.rm(a,{force:!0})}catch{}throw l}}async function kt(e,t,r={}){await cx(e,t,r)}async function Me(e,t,r={}){await kt(e,JSON.stringify(t,null,2)+`
144
+ `,r)}var se=A(()=>{"use strict";bt()});function dx(e,t){return uu[e][t]}function Uo(e){return Gm.get(e.trim().toLocaleLowerCase("en-US"))??null}function Um(e){return du.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ko(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${dx(e,r)}
145
145
  `).join(`
146
- `)}var uu,lx,ux,Gm,du,Gr=A(()=>{"use strict";uu={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:"验证预期"}},lx={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:"结论"}},ux={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:"结论"}},Gm=new Map,du=new Map;for(let e of Object.keys(uu)){for(let[t,r]of Object.entries(uu[e]))Gm.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(lx[e]))du.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(ux[e]))du.set(r.toLocaleLowerCase("en-US"),t)}});import fr from"path";function gx(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||fr.posix.isAbsolute(r)||fr.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 xi(e){let t=gx(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ev(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 Qo(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||fr.posix.isAbsolute(i)||fr.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 $t(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tv(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 Zo(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>Yo)throw new Error(`${t} exceeds ${Yo} 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>Xo)throw new Error(`${t} contains more than ${Xo} wildcard tokens`);return e}function Qm(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=>Zo(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function pu(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 wx(e){if(e===void 0)return{...at,include:[...at.include],exclude:[...at.exclude]};let t=$t(e,"native.snapshot");return{include:Qm(t.include,"native.snapshot.include",at.include),exclude:Qm(t.exclude,"native.snapshot.exclude",at.exclude),max_files:pu(t.max_files,at.max_files,"native.snapshot.max_files"),max_total_bytes:pu(t.max_total_bytes,at.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:pu(t.max_duration_ms,at.max_duration_ms,"native.snapshot.max_duration_ms")}}function yx(e){if(e===void 0)return;let t=$t(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=$t(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:xi(i),toArtifactRoot:xi(n),stage:a,...o?{cleanup:o}:{}}}function Nx(e){if(e===void 0)return;let t=$t(e,"native.finish");if(t.pull_request===void 0)return{};let r=$t(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(fr.posix.isAbsolute(i[0])||fr.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??px;if(!Number.isSafeInteger(n)||n<1||n>Xm)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Xm}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function bx(e,t={}){let r=$t(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??Zm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=yx(r.pending_root_move),c=Nx(r.finish);return{artifact_root:xi(i),language:tv(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:wx(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function kx(e){let t=$t(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:ev(t.artifact_layout),language:tv(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Sx(e){let r=$t(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)=>Qo(i,`hook.allow_paths[${n}]`)))]}}function Ex(e){if(e===void 0)return{...fu};let t=$t(e,"memory"),r=t.learning??fu.learning,i=t.retrieval??fu.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 mu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Cx(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")||fr.posix.isAbsolute(r)||fr.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>Km)throw new Error(`${t} exceeds ${Km} 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>Ym)throw new Error(`${t} contains more than ${Ym} wildcard tokens`);return r}function xx(e){let r=mu(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)=>Cx(i,`knowledge.local.include[${n}]`)))]}}function Px(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 Rx(e){let t=mu(e,"knowledge.remote"),r=Px(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 Ax(e){if(e===void 0)return{...fx};let t=mu(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:xx(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Rx(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 _x(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ix(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 Xn(e,t={}){let r=(0,hu.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=_x(n.ambient_resume),o=n.hook===void 0?void 0:Sx(n.hook),s=Ex(n.memory),c=Ax(n.knowledge),l=n.native===void 0?void 0:bx(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:kx(n.classic),d=Ix(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}:{}}}var hu,Yn,Yo,Xo,Km,Ym,Zm,fu,fx,px,Xm,hx,mx,vx,at,pr=A(()=>{"use strict";hu=fi(Jr(),1),Yn=64*1024,Yo=1024,Xo=64,Km=1024,Ym=64,Zm=5,fu={learning:!0,retrieval:!0},fx={provider:"local"},px=12e4,Xm=6e5,hx=[".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/**"],mx=["**/.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"],vx=[...hx,...mx].sort((e,t)=>e.localeCompare(t,"en")),at={include:["**/*"],exclude:[...vx],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as es,promises as Ur}from"fs";function vu(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function rv(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Qn(e){return{dev:e.dev,ino:e.ino,birthtime:vu(e)}}function ts(e,t){let r=Qn(e),i=Qn(t);return Fe(r,i)?W(r,i):W(r,i)&&vu(e)===vu(t)&&rv(e)===rv(t)&&e.size===t.size}async function Pi(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 Ur.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new kt("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new kt("too-large",`${i} exceeds ${t} bytes`);let o=await Ur.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Qn(a)});let s=process.platform==="win32"?es.O_RDONLY:es.O_RDONLY|es.O_NOFOLLOW|es.O_NONBLOCK,c;try{c=await Ur.open(e,s)}catch(l){throw l.code==="ELOOP"?new kt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Ur.lstat(e,{bigint:n}),Ur.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ts(a,l)||!ts(a,u))throw new kt("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Qn(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 kt("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),Ur.lstat(e,{bigint:n}),Ur.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!ts(a,h)||!ts(a,m))throw new kt("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Qn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var kt,Zn=A(()=>{"use strict";Un();kt=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as rs}from"fs";import hr from"path";function Tx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function gu(e,t){let r=hr.relative(e,t);return r===""||!hr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${hr.sep}`)}async function iv(e,t){let r=hr.resolve(e),i=await rs.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return rs.realpath(r)}async function nv(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=hr.join(n,r[a]);let o;try{o=await rs.lstat(n)}catch(u){if(Tx(u))return{exists:!1,kind:"missing"};throw u}let s=hr.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 rs.realpath(n);if(!gu(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 Ri(e,t,r){let i=Qo(t,r.label),n=hr.resolve(e),a=await iv(n,r.label),o=i.split("/"),s=hr.resolve(n,...o);if(!gu(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await nv(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function mr(e,t,r,i){let n=await Ri(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 iv(n.projectRoot,i.label);return Pi(n.target,r,{...i,verify:async(o,s)=>{if(!gu(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await nv(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Kr=A(()=>{"use strict";Zn();pr()});import{createHash as jx}from"crypto";function $x(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function is(e,t={}){return(await ns(e,t)).document}async function Ox(e){try{return(await mr(e,ea,Yn,{label:ea})).bytes}catch(t){if($x(t))return null;throw t}}function Hx(e){return e?{exists:!0,sha256:jx("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ns(e,t={}){let r=await Ox(e);return{document:r?Xn(r.toString("utf8"),t):null,identity:Hx(r)}}async function wu(e){return(await is(e))?.config??null}var ea,Ai=A(()=>{"use strict";pr();Kr();ea=".comet/config.yaml"});var _i=A(()=>{"use strict";Un()});var M0,yu=A(()=>{"use strict";_i();Ai();Kr();M0=16*1024});var ku=A(()=>{"use strict";_i();pr();Ai();Kr();yu()});import{existsSync as ov,promises as vr}from"fs";import z from"path";import Fx from"os";async function Su(e){try{return await vr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mx(e){try{let t=await vr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ti(e,t){let r=z.relative(e,t);return r===""||!z.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${z.sep}`)}async function Ii(e){let t=[],r=e;for(;!await Su(r);){let n=z.dirname(r);if(n===r)break;t.push(z.basename(r)),r=n}let i=await vr.realpath(r);return z.resolve(i,...t.reverse())}async function Eu(e){try{return(await vr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xu(e){let t=z.resolve(e);try{(await vr.stat(t)).isDirectory()||(t=z.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=z.resolve(Fx.homedir());for(;;){if(!(t===i&&r!==i)){let o=z.join(t,...Cu.split("/")),s=t===r||await Mx(o);if(await Su(o)&&s)return t}if(await Su(z.join(t,".git")))return t;let a=z.dirname(t);if(a===t)return r;t=a}}function Pu(e){return xi(e)}async function Wx(e,t){let r=Pu(t),i=z.resolve(e,...r.split("/")),n=await vr.realpath(e),a=await Ii(i);if(!Ti(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ot(e,t){let r=Pu(t),i=await Wx(e,r),n=z.join(i,"comet");if(await Eu(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ii(i),Ii(n)]);if(!Ti(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=z.resolve(e),c=z.join(s,".comet","runtime","native");if(await Eu(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([vr.realpath(s),Ii(c)]);if(!Ti(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:z.join(e,...Cu.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:z.join(n,"specs"),changesDir:z.join(n,"changes"),archiveDir:z.join(n,"archive"),runtimeDir:c,changesRuntimeDir:z.join(c,"changes"),locksDir:z.join(c,"locks"),transactionsDir:z.join(c,"transactions")}}function cv(e){if(!qx.test(e))throw new Error(`Invalid Native change name: ${e}`)}function gr(e,t){cv(t);let r=z.join(e.changesRuntimeDir,t);if(!F(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function lv(e,t){cv(t);let r=z.join(e.changesDir,t,"runtime");if(!F(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function K(e,t){let r=gr(e,t);if(ov(r))return r;let i=lv(e,t);return ov(i)?i:r}async function sv(e){try{let t=await vr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ru(e,t){let r=gr(e,t),i=lv(e,t),[n,a]=await Promise.all([sv(r),sv(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function wr(e,t){if(!t.startsWith("runtime/")||z.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=z.resolve(e,...t.slice(8).split("/"));if(!F(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function me(e,t){let r=z.resolve(t);if(F(e.runtimeDir,r))return e.runtimeDir;if(F(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function F(e,t){return Ti(z.resolve(e),z.resolve(t))}async function G(e,t){let r=z.resolve(e),i=z.resolve(t);if(!Ti(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Eu(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ii(r),Ii(i)]);if(!Ti(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Cu,qx,Y=A(()=>{"use strict";pr();Cu=".comet/config.yaml",qx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function Ae(e){let t=(await is(e))?.config??null;return t?.native?t:null}var Au,as,We=A(()=>{"use strict";pr();Ai();ku();se();Y();Au=at,as=Zo});import{AsyncLocalStorage as Jx}from"async_hooks";var hH,mH,ra=A(()=>{"use strict";Zn();Y();Nt();hH=16*1024,mH=new Jx});import dv from"node:path";function Zx(e,t){return e<t?-1:e>t?1:0}function hv(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function mv(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function eP(e){if(!Xx.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=Qx.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function tP(e,t){let r=hv(e.text,Ht.maxTextBytes),i=e.context.slice(0,Ht.maxContextItems).map(n=>hv(n,Ht.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function gv(e){let t=eP({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(Zx),n=i.slice(0,Ht.maxFailedCheckIds),a=e.criteria.slice(t,t+Ht.maxItems);for(let c of a){let l=[...r,tP(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?mv(e.acceptanceHash,u):null,limits:{...Ht}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Ht.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?mv(e.acceptanceHash,o):null,limits:{...Ht}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Ht.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Iu(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function _u(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function vv(e){return e.includes("-->")||e.includes("--!>")}function*ji(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
146
+ `)}var uu,lx,ux,Gm,du,Gr=A(()=>{"use strict";uu={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:"验证预期"}},lx={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:"结论"}},ux={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:"结论"}},Gm=new Map,du=new Map;for(let e of Object.keys(uu)){for(let[t,r]of Object.entries(uu[e]))Gm.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(lx[e]))du.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(ux[e]))du.set(r.toLocaleLowerCase("en-US"),t)}});import fr from"path";function gx(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||fr.posix.isAbsolute(r)||fr.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 xi(e){let t=gx(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ev(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 Qo(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||fr.posix.isAbsolute(i)||fr.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 Ot(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tv(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 Zo(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>Yo)throw new Error(`${t} exceeds ${Yo} 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>Xo)throw new Error(`${t} contains more than ${Xo} wildcard tokens`);return e}function Qm(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=>Zo(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function pu(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 wx(e){if(e===void 0)return{...ot,include:[...ot.include],exclude:[...ot.exclude]};let t=Ot(e,"native.snapshot");return{include:Qm(t.include,"native.snapshot.include",ot.include),exclude:Qm(t.exclude,"native.snapshot.exclude",ot.exclude),max_files:pu(t.max_files,ot.max_files,"native.snapshot.max_files"),max_total_bytes:pu(t.max_total_bytes,ot.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:pu(t.max_duration_ms,ot.max_duration_ms,"native.snapshot.max_duration_ms")}}function yx(e){if(e===void 0)return;let t=Ot(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=Ot(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:xi(i),toArtifactRoot:xi(n),stage:a,...o?{cleanup:o}:{}}}function Nx(e){if(e===void 0)return;let t=Ot(e,"native.finish");if(t.pull_request===void 0)return{};let r=Ot(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(fr.posix.isAbsolute(i[0])||fr.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??px;if(!Number.isSafeInteger(n)||n<1||n>Xm)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Xm}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function bx(e,t={}){let r=Ot(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??Zm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=yx(r.pending_root_move),c=Nx(r.finish);return{artifact_root:xi(i),language:tv(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:wx(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function kx(e){let t=Ot(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:ev(t.artifact_layout),language:tv(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Sx(e){let r=Ot(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)=>Qo(i,`hook.allow_paths[${n}]`)))]}}function Ex(e){if(e===void 0)return{...fu};let t=Ot(e,"memory"),r=t.learning??fu.learning,i=t.retrieval??fu.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 mu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Cx(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")||fr.posix.isAbsolute(r)||fr.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>Km)throw new Error(`${t} exceeds ${Km} 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>Ym)throw new Error(`${t} contains more than ${Ym} wildcard tokens`);return r}function xx(e){let r=mu(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)=>Cx(i,`knowledge.local.include[${n}]`)))]}}function Px(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 Rx(e){let t=mu(e,"knowledge.remote"),r=Px(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 Ax(e){if(e===void 0)return{...fx};let t=mu(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:xx(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Rx(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 _x(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Ix(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 Xn(e,t={}){let r=(0,hu.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=_x(n.ambient_resume),o=n.hook===void 0?void 0:Sx(n.hook),s=Ex(n.memory),c=Ax(n.knowledge),l=n.native===void 0?void 0:bx(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:kx(n.classic),d=Ix(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}:{}}}var hu,Yn,Yo,Xo,Km,Ym,Zm,fu,fx,px,Xm,hx,mx,vx,ot,pr=A(()=>{"use strict";hu=fi(Jr(),1),Yn=64*1024,Yo=1024,Xo=64,Km=1024,Ym=64,Zm=5,fu={learning:!0,retrieval:!0},fx={provider:"local"},px=12e4,Xm=6e5,hx=[".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/**"],mx=["**/.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"],vx=[...hx,...mx].sort((e,t)=>e.localeCompare(t,"en")),ot={include:["**/*"],exclude:[...vx],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as es,promises as Ur}from"fs";function vu(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function rv(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Qn(e){return{dev:e.dev,ino:e.ino,birthtime:vu(e)}}function ts(e,t){let r=Qn(e),i=Qn(t);return Fe(r,i)?W(r,i):W(r,i)&&vu(e)===vu(t)&&rv(e)===rv(t)&&e.size===t.size}async function Pi(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 Ur.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new St("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new St("too-large",`${i} exceeds ${t} bytes`);let o=await Ur.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Qn(a)});let s=process.platform==="win32"?es.O_RDONLY:es.O_RDONLY|es.O_NOFOLLOW|es.O_NONBLOCK,c;try{c=await Ur.open(e,s)}catch(l){throw l.code==="ELOOP"?new St("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Ur.lstat(e,{bigint:n}),Ur.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ts(a,l)||!ts(a,u))throw new St("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Qn(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 St("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),Ur.lstat(e,{bigint:n}),Ur.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!ts(a,h)||!ts(a,m))throw new St("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Qn(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var St,Zn=A(()=>{"use strict";Un();St=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as rs}from"fs";import hr from"path";function Tx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function gu(e,t){let r=hr.relative(e,t);return r===""||!hr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${hr.sep}`)}async function iv(e,t){let r=hr.resolve(e),i=await rs.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return rs.realpath(r)}async function nv(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=hr.join(n,r[a]);let o;try{o=await rs.lstat(n)}catch(u){if(Tx(u))return{exists:!1,kind:"missing"};throw u}let s=hr.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 rs.realpath(n);if(!gu(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 Ri(e,t,r){let i=Qo(t,r.label),n=hr.resolve(e),a=await iv(n,r.label),o=i.split("/"),s=hr.resolve(n,...o);if(!gu(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await nv(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function mr(e,t,r,i){let n=await Ri(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 iv(n.projectRoot,i.label);return Pi(n.target,r,{...i,verify:async(o,s)=>{if(!gu(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await nv(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Kr=A(()=>{"use strict";Zn();pr()});import{createHash as jx}from"crypto";function $x(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function is(e,t={}){return(await ns(e,t)).document}async function Ox(e){try{return(await mr(e,ea,Yn,{label:ea})).bytes}catch(t){if($x(t))return null;throw t}}function Hx(e){return e?{exists:!0,sha256:jx("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ns(e,t={}){let r=await Ox(e);return{document:r?Xn(r.toString("utf8"),t):null,identity:Hx(r)}}async function wu(e){return(await is(e))?.config??null}var ea,Ai=A(()=>{"use strict";pr();Kr();ea=".comet/config.yaml"});var _i=A(()=>{"use strict";Un()});var M0,yu=A(()=>{"use strict";_i();Ai();Kr();M0=16*1024});var ku=A(()=>{"use strict";_i();pr();Ai();Kr();yu()});import{existsSync as ov,promises as vr}from"fs";import z from"path";import Fx from"os";async function Su(e){try{return await vr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mx(e){try{let t=await vr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ti(e,t){let r=z.relative(e,t);return r===""||!z.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${z.sep}`)}async function Ii(e){let t=[],r=e;for(;!await Su(r);){let n=z.dirname(r);if(n===r)break;t.push(z.basename(r)),r=n}let i=await vr.realpath(r);return z.resolve(i,...t.reverse())}async function Eu(e){try{return(await vr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xu(e){let t=z.resolve(e);try{(await vr.stat(t)).isDirectory()||(t=z.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=z.resolve(Fx.homedir());for(;;){if(!(t===i&&r!==i)){let o=z.join(t,...Cu.split("/")),s=t===r||await Mx(o);if(await Su(o)&&s)return t}if(await Su(z.join(t,".git")))return t;let a=z.dirname(t);if(a===t)return r;t=a}}function Pu(e){return xi(e)}async function Wx(e,t){let r=Pu(t),i=z.resolve(e,...r.split("/")),n=await vr.realpath(e),a=await Ii(i);if(!Ti(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ht(e,t){let r=Pu(t),i=await Wx(e,r),n=z.join(i,"comet");if(await Eu(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ii(i),Ii(n)]);if(!Ti(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=z.resolve(e),c=z.join(s,".comet","runtime","native");if(await Eu(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([vr.realpath(s),Ii(c)]);if(!Ti(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:z.join(e,...Cu.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:z.join(n,"specs"),changesDir:z.join(n,"changes"),archiveDir:z.join(n,"archive"),runtimeDir:c,changesRuntimeDir:z.join(c,"changes"),locksDir:z.join(c,"locks"),transactionsDir:z.join(c,"transactions")}}function cv(e){if(!qx.test(e))throw new Error(`Invalid Native change name: ${e}`)}function gr(e,t){cv(t);let r=z.join(e.changesRuntimeDir,t);if(!F(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function lv(e,t){cv(t);let r=z.join(e.changesDir,t,"runtime");if(!F(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function K(e,t){let r=gr(e,t);if(ov(r))return r;let i=lv(e,t);return ov(i)?i:r}async function sv(e){try{let t=await vr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ru(e,t){let r=gr(e,t),i=lv(e,t),[n,a]=await Promise.all([sv(r),sv(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function wr(e,t){if(!t.startsWith("runtime/")||z.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=z.resolve(e,...t.slice(8).split("/"));if(!F(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function me(e,t){let r=z.resolve(t);if(F(e.runtimeDir,r))return e.runtimeDir;if(F(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function F(e,t){return Ti(z.resolve(e),z.resolve(t))}async function G(e,t){let r=z.resolve(e),i=z.resolve(t);if(!Ti(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Eu(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ii(r),Ii(i)]);if(!Ti(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Cu,qx,Y=A(()=>{"use strict";pr();Cu=".comet/config.yaml",qx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function Ae(e){let t=(await is(e))?.config??null;return t?.native?t:null}var Au,as,We=A(()=>{"use strict";pr();Ai();ku();se();Y();Au=ot,as=Zo});import{AsyncLocalStorage as Jx}from"async_hooks";var hH,mH,ra=A(()=>{"use strict";Zn();Y();bt();hH=16*1024,mH=new Jx});import dv from"node:path";function Zx(e,t){return e<t?-1:e>t?1:0}function hv(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function mv(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function eP(e){if(!Xx.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=Qx.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function tP(e,t){let r=hv(e.text,Dt.maxTextBytes),i=e.context.slice(0,Dt.maxContextItems).map(n=>hv(n,Dt.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function gv(e){let t=eP({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(Zx),n=i.slice(0,Dt.maxFailedCheckIds),a=e.criteria.slice(t,t+Dt.maxItems);for(let c of a){let l=[...r,tP(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?mv(e.acceptanceHash,u):null,limits:{...Dt}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Dt.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?mv(e.acceptanceHash,o):null,limits:{...Dt}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Dt.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Iu(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function _u(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function vv(e){return e.includes("-->")||e.includes("--!>")}function*ji(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
147
147
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
148
148
  `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=_u(l,t);else if(r)vv(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=_u(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!vv(f))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function rP(e){return[...ji(e)].map(({line:t,body:r})=>({line:t,body:r}))}function os(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function iP(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Tu(e,t,r,i=[],n="content-hash"){let a=os(r),o=t.replaceAll("\\","/").trim(),s=i.map(os);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${j(Gx,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function ju(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function nP(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of ji(e)){n=s+1;let c=o?Iu(a):null;c?.level===1&&(Uo(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function $u(e,t="brief.md",r=ia.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=nP(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ji(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ji(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),ju(o.map(l=>Tu("brief-example",t,l.join(`
149
149
  `),[],i)),"Brief",i)}function Ou(e,t="spec.md",r=ia.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Tu("spec-scenario",t,[o.title,...o.body].join(`
150
150
  `),o.context,i)),o=null}};for(let{line:c,body:l}of ji(e)){let u=l?Iu(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=os(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),ju(n,"Specification",i)}function wv(e,t="spec.md",r=ia.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Tu("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of ji(e)){let f=d?Iu(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||_u(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),ju(n,"Specification mandatory requirements",i)}function aP(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||iP(r)||dv.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=dv.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!Yx.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function oP(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!Kx.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function yv(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=oP(r,i),a=n.acceptance_id;if(typeof a!="string"||!Ux.test(a))throw new Error(`Acceptance evidence entry ${i} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return aP(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Nv(e){let t=rP(e);if(t.some(({line:l,body:u})=>!u&&(l===fv||l===pv)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===fv?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===pv?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
151
- `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=yv(o),c=sP(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function sP(e){let t=yv([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var Gx,Ux,Kx,Yx,Xx,Qx,Ht,ia,fv,pv,na=A(()=>{"use strict";Gr();pe();Gx="comet.native.acceptance.v1",Ux=/^acceptance-[a-f0-9]{64}$/u,Kx=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),Yx=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,Xx=/^[a-f0-9]{64}$/u,Qx=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;Ht=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ia=Object.freeze({maxCriteria:1024}),fv="<!-- comet-native:acceptance-evidence:start -->",pv="<!-- comet-native:acceptance-evidence:end -->"});var Hu=A(()=>{"use strict";na()});function Du(){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 $i,ss,bv,aa=A(()=>{"use strict";$i="comet.native.v4",ss="comet.native.local-execution.v4",bv=["multi-session","single-session"]});var Mu={};ep(Mu,{NativePortableStateVersionConflictError:()=>oa,appendNativePortableHistory:()=>Fu,compareAndSwapNativePortableState:()=>Cv,createNativePortableState:()=>Ev,parseNativePortableState:()=>_e,readNativePortableState:()=>Dt,writeNativePortableState:()=>qu});import{promises as cP}from"node:fs";function Ce(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xe(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ve(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 Lu(e,t){return e===null?null:ve(e,t)}function kv(e,t){let r=ve(e,t);if(!fP.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Oi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function re(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 hP(e,t){return e===null?null:re(e,t,Number.MIN_SAFE_INTEGER)}function ce(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function St(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function us(e,t){return St(e,t,(r,i)=>ve(r,`${t}[${i}]`))}function Yr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Hi(e,t){let r=ve(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Vu(e,t,r=!1){let i=ve(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 ze(e,t){let r=Ce(e,t);return xe(r,new Set(["text","truncated"]),t),{text:ve(r.text,`${t}.text`,{empty:!0}),truncated:Oi(r.truncated,`${t}.truncated`)}}function mP(e,t){let r=`Native spec_changes[${t}]`,i=Ce(e,r);xe(i,new Set(["capability","operation","source"]),r);let n=ve(i.capability,`${r}.capability`);if(!uP.test(n))throw new Error(`${r}.capability is invalid`);let a=ce(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Vu(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 vP(e){let t="Native workspace",r=Ce(e,t);xe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ce(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Lu(r.change_branch,`${t}.change_branch`),a=Lu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ce(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 gP(e){let t="Native loop",r=Ce(e,t);xe(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=us(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Yr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ce(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ce(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:re(r.goal_cycle,`${t}.goal_cycle`,1),iteration:re(r.iteration,`${t}.iteration`),attempt:re(r.attempt,`${t}.attempt`),retry_epoch:re(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:re(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:re(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:re(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Lu(r.next_action,`${t}.next_action`)}}function wP(e,t){let r=`Native acceptance[${t}]`,i=Ce(e,r);xe(i,new Set(["id","source","text","result","reason"]),r);let n=ve(i.id,`${r}.id`);if(!dP.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Vu(i.source,`${r}.source`),text:ve(i.text,`${r}.text`),result:ce(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ze(i.reason,`${r}.reason`)}}function yP(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Ce(e,r);return xe(i,new Set(["name","result","note"]),r),{name:ze(i.name,`${r}.name`),result:ce(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ze(i.note,`${r}.note`)}}function NP(e){let t="Native builder_handoff",r=Ce(e,t);xe(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=us(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Yr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Ce(r.review,`${t}.review`);return n&&xe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ve(r.candidate_id,`${t}.candidate_id`),identity_provider:ve(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ve(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:re(r.iteration,`${t}.iteration`,1),summary:ze(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:St(r.checks,`${t}.checks`,yP),checks_truncated:Oi(r.checks_truncated,`${t}.checks_truncated`),known_limits:St(r.known_limits,`${t}.known_limits`,(a,o)=>ze(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Oi(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ce(n.status,["passed"],`${t}.review.status`),summary:ze(n.summary,`${t}.review.summary`),reviewer_execution_ref:ve(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Hi(r.submitted_at,`${t}.submitted_at`)}}function bP(e,t){let r=`Native blockers[${t}]`,i=Ce(e,r);xe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=us(i.acceptance_ids,`${r}.acceptance_ids`);return Yr(n,`${r}.acceptance_ids`),{owner:ce(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ze(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ce(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function kP(e,t){let r=`Native verification.checks[${t}]`,i=Ce(e,r);return xe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ve(i.id,`${r}.id`),name:ze(i.name,`${r}.name`),argv_display:St(i.argv_display,`${r}.argv_display`,(n,a)=>ze(n,`${r}.argv_display[${a}]`)),argv_truncated:Oi(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Vu(i.cwd_ref,`${r}.cwd_ref`,!0),status:ce(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:hP(i.exit_code,`${r}.exit_code`),duration_ms:re(i.duration_ms,`${r}.duration_ms`)}}function SP(e){let t="Native verification",r=Ce(e,t);xe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=St(r.checks,`${t}.checks`,kP);Yr(i.map(a=>a.id),`${t}.checks IDs`);let n=ve(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ve(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ve(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:re(r.iteration,`${t}.iteration`,1),attempt:re(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ce(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ce(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ze(r.summary,`${t}.summary`),risks:St(r.risks,`${t}.risks`,(a,o)=>ze(a,`${t}.risks[${o}]`)),risks_truncated:Oi(r.risks_truncated,`${t}.risks_truncated`),completed_at:Hi(r.completed_at,`${t}.completed_at`)}}function Sv(e,t){let r=`Native history[${t}]`,i=Ce(e,r);xe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=us(i.unresolved_ids,`${r}.unresolved_ids`);return Yr(n,`${r}.unresolved_ids`),{goal_cycle:re(i.goal_cycle,`${r}.goal_cycle`,1),iteration:re(i.iteration,`${r}.iteration`),attempt:re(i.attempt,`${r}.attempt`),outcome:ce(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ze(i.summary,`${r}.summary`),completed_at:Hi(i.completed_at,`${r}.completed_at`)}}function EP(e){let t="Native history_overflow.outcome_counts",r=Ce(e,t),i=["pass","fail","blocked","execution-error","recovery"];return xe(r,new Set(i),t),{pass:re(r.pass,`${t}.pass`),fail:re(r.fail,`${t}.fail`),blocked:re(r.blocked,`${t}.blocked`),"execution-error":re(r["execution-error"],`${t}.execution-error`),recovery:re(r.recovery,`${t}.recovery`)}}function CP(e){let t="Native history_overflow",r=Ce(e,t);xe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=re(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Hi(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Hi(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=EP(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 xP(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 PP(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 _e(e){let t=Ce(e,"Native portable state");if(xe(t,pP,"Native portable state"),t.schema!==$i)throw new Error(`Native portable state schema must be ${$i}`);let r=ve(t.name,"Native state name");if(!lP.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=St(t.spec_changes,"Native spec_changes",mP);Yr(i.map(s=>s.capability),"Native spec change capabilities");let n=St(t.acceptance,"Native acceptance",wP);Yr(n.map(s=>s.id),"Native acceptance IDs");let a=St(t.history,"Native history",Sv);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:$i,name:r,language:ce(t.language,["en","zh-CN"],"Native state language"),phase:ce(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ce(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:re(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:kv(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:kv(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ce(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:vP(t.workspace),loop:gP(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:NP(t.builder_handoff),blockers:St(t.blockers,"Native blockers",bP),verification:t.verification===null?null:SP(t.verification),history:a,history_overflow:CP(t.history_overflow),verification_result:ce(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ce(t.verification_report,["verification.md"],"Native verification_report"),archived:Oi(t.archived,"Native archived"),created_at:Hi(t.created_at,"Native created_at")};return xP(o),PP(o),o}function Ev(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return _e({schema:$i,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:Du(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Fu(e,t){let r=_e(e),i=Sv(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return _e({...r,history:n,history_overflow:a})}function RP(e,t){let r=(0,ls.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 Dt(e){let t=await cP.readFile(e,"utf8");return _e(RP(t,"Native portable state"))}async function qu(e,t,r={}){let i=_e(t);await bt(e,(0,ls.stringify)(i),r)}async function AP(e,t){let r=cs.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);cs.set(e,a),await r;try{return await t()}finally{i(),cs.get(e)===a&&cs.delete(e)}}async function Cv(e){return AP(e.file,async()=>{let t=re(e.expectedStateVersion,"Native expected state version",1),r=_e(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Dt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new oa(t,i.state_version);return await qu(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Dt(e.file);if(n.state_version!==t)throw new oa(t,n.state_version)}}),r})}var ls,lP,uP,dP,fP,pP,oa,cs,yr=A(()=>{"use strict";ls=fi(Jr(),1);se();aa();lP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dP=/^A[1-9][0-9]*$/u,fP=/^[a-f0-9]{64}$/u,pP=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"]),oa=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};cs=new Map});var ds=A(()=>{"use strict"});var Nr,br,kr,Di,Bi,sa,fs=A(()=>{"use strict";Nr="comet.native.v3",br="comet.native.v2",kr="comet.native.v1",Di="comet.native.transition.v3",Bi="comet.native.transition.v2",sa="comet.native.transition.v1"});var Pv=A(()=>{"use strict";ge();Hu();yr();ds();aa();fs()});var Rv,VH,FH,Wu=A(()=>{"use strict";it();Pv();Rv="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",VH=new RegExp(`^portable-archive-(${Rv})\\.json$`,"u"),FH=new RegExp(`^portable-migration-(${Rv})\\.json$`,"u")});import{createHash as _P}from"node:crypto";import{constants as ps,promises as He}from"node:fs";import ot from"node:path";import{TextDecoder as IP}from"node:util";function ms(e,t){let r=ot.relative(e,t);return r===""||!ot.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ot.sep}`)}function Av(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function TP(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function hs(e,t){return W({...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 zu(e,t){let r=await He.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ju(e,t,r){let i=ot.resolve(e),n=ot.resolve(t);if(!ms(i,n))throw new Error(`${r} is outside its managed root`);let a=[await zu(i,r)],o=i;for(let s of ot.relative(i,n).split(ot.sep).filter(Boolean)){await Et(a,r),o=ot.join(o,s);let c=await zu(o,r);if(!ms(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Et(a,r),a}async function Et(e,t){for(let r of e){let i=await He.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!TP(r,i)||await He.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function $P(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 Bt(e){let t=Av(e.maxBytes),r=ot.resolve(e.file),i=await Ju(e.root,ot.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>zu(ot.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Et(i,e.label);let a=await He.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=jP(a),s=await He.realpath(r);if(!ms(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ms(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ps.O_RDONLY:ps.O_RDONLY|ps.O_NOFOLLOW|ps.O_NONBLOCK,l=await He.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([He.lstat(r),He.realpath(r)]);if(await Et(i,e.label),await Et(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!hs(o,u)||!hs(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await $P(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),He.lstat(r),He.realpath(r)]);if(await Et(i,e.label),await Et(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!hs(o,v)||!hs(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:_P("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function _v(e){let t=await Bt(e),r;try{r=new IP("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 ca(e){let t=await Ju(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await He.readdir(e.directory,{withFileTypes:!0});else{let i=Av(e.maxEntries);r=[];let n=await He.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 Et(t,e.label),{entries:r,verify:()=>Et(t,e.label)}}async function Gu(e){let t=await Ju(e.root,e.directory,e.label);return{verify:()=>Et(t,e.label)}}var st=A(()=>{"use strict";se();Nt()});import{TextDecoder as HP}from"util";var iD,nD,aD,oD,sD,vs=A(()=>{"use strict";se();Y();st();iD=256*1024,nD=1024*1024,aD=16*1024,oD=64*1024*1024,sD=new HP("utf-8",{fatal:!0})});var ct=A(()=>{"use strict";We();ra();Wu();vs()});var Ov=A(()=>{"use strict"});import{createHash as Hv}from"crypto";import{createReadStream as BP}from"fs";async function Uu(e){let t=Hv("sha256");for await(let r of BP(e))t.update(r);return t.digest("hex")}function X(e){return Hv("sha256").update(e).digest("hex")}var Ct=A(()=>{"use strict"});import{createHash as bs}from"crypto";import{spawn as zv}from"node:child_process";import{promises as Z}from"fs";import B from"path";function Gv(e){let t=e.deadlineMs??iR;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function lt(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return lt(e)>=1}function Ku(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Mi(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function sR(e){let t={...oR,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function cR(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&B.win32.isAbsolute(i)?B.win32.resolve(i):"C:\\Windows",a=B.win32.join(n,"System32","taskkill.exe");if(!B.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=zv(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),nR),u.unref()}catch{d(!1)}});for(let s=0;s<aR;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function rd(e,t,r,i){let n=lt(e);if(n<1)throw Ku();let a=e.gitProcess,o=zv(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=cR(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ku(v.error):Ku()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Uv(e){let t={...td,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ws(e,t,r,i=Qu){let{child:n,completion:a}=rd(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,i-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>i&&(u=!0)}),n.stderr.on("data",p=>{if(c>=zi)return;let v=zi-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Yu(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function ua(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=rd(e,t,r,i.stdin!==void 0),c=[],l=bs("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,g=!1,b=!1,S=w=>{let E=0;for(;E<w.byteLength;){let k=w.indexOf(0,E),x=k<0?w.byteLength:k,N=w.subarray(E,x);if(!m&&N.byteLength>0&&(h.byteLength+N.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),m=!0,g=!0):h=Buffer.concat([h,N])),k<0)break;v+=1,h.byteLength===0&&!m&&(b=!0);let y=h.byteLength+1;!m&&v<=i.maxRecords&&p+y<=i.maxBytes?(c.push(h),p+=y):g=!0,h=Buffer.alloc(0),m=!1,E=k+1}};o.stdout.on("data",w=>{l.update(w),f+=w.byteLength,f>i.maxBytes&&(g=!0);let E=i.outputChunkBytes;if(E===void 0){S(w);return}for(let k=0;k<w.byteLength;k+=E)S(w.subarray(k,Math.min(w.byteLength,k+E)))}),o.stderr.on("data",w=>{if(d>=zi)return;let E=zi-d,k=Buffer.from(w).subarray(0,E);u.push(k),d+=k.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:w,spawnError:E})=>{let k=i.acceptedExitCodes??[0];if(w!==null&&k.includes(w)&&E===null&&!b&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${E?`: ${E.message}`:b||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function ys(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function lR(e,t,r){if(r.length===0)return new Set;let i=await ua(e,t,["check-ignore","--no-index","-z","--stdin"],{...td,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=ys(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function uR(e,t,r){let{child:i,completion:n}=rd(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=zi)return;let d=zi-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Wi(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||B.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||B.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function dR(e,t){return e.map(r=>{let i=Wi(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function fR(e){let t=B.resolve(e);for(;;){try{return await Z.lstat(B.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=B.dirname(t);if(r===t)return!1;t=r}}async function Kv(e,t,r,i={}){let n=B.resolve(t.projectRoot),a=B.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=B.relative(n,B.resolve(f)).replaceAll("\\","/"),v=Wi(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},l=await ua(e,n,["ls-files","--stage","-z",...s],c);await i.afterStageBefore?.();let u=await ua(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await i.afterCombined?.();let d=await ua(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Yv(e){return{stageBefore:Yu(e.stagedBefore),combined:Yu(e.combined),stageAfter:Yu(e.stagedAfter)}}async function Xv(e,t,r=td,i={}){let n=B.resolve(t.projectRoot);if(!await fR(n))return null;let a;try{a=await ws(e,n,["rev-parse","--is-inside-work-tree"])}catch(b){throw Mi(b)?b:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:b})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Kv(e,t,r,i)}catch(b){throw Mi(b)?b:new Error("Native Git snapshot provider failed after repository detection",{cause:b})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=b=>{for(let S of b){let w=ys(S),E=w.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(w.slice(0,E))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=Wi(w.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),k.stage==="0"&&d.set(x,k.objectId),k.mode==="160000"&&k.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(ys),h=dR(v,"combined"),m=new Set(h.filter(b=>!u.has(b))),g=new Set(h.filter((b,S)=>!u.has(b)&&v[S].endsWith("/")));for(let b of f)g.delete(b);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:Yv(o)}}function Cr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Dv(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function pR(e,t){return!Cr(e.stageBefore,e.stageAfter)||!Cr(e.stageAfter,t.stageBefore)||!Cr(e.combined,t.combined)||!Cr(t.stageBefore,t.stageAfter)}async function Qv(e,t,r,i,n){let a;try{a=await Kv(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Mi(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=i.initialFence,s=Yv(a),c=Dv(o)||Dv(s),l=pR(o,s);c&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(i.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:X(`comet.native.git-selection-overflow.v2
152
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}function mR(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Bv(e){let t=B.resolve(e.paths.projectRoot),r=B.resolve(e.paths.nativeRoot),i=B.resolve(e.paths.runtimeDir),n=B.resolve(e.paths.configFile),a=B.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>lt(e.execution)>=1?!0:(p=!0,h=!0,!1),g=w=>{let E=Buffer.from(`${w.type}\0${w.path}`,"utf8"),k=bs("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=k[x];if(l=l+BigInt(`0x${k.toString("hex")}`)&hR,d+=1,f+=E.byteLength,Buffer.byteLength(w.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(w)},b=async w=>{if(h||!m())return;let E;try{E=await Z.opendir(w)}catch(C){if(!m())return;if(!ue(C)&&!le(C)||w===t&&ue(C))throw C;v||=le(C),p||=ue(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let k=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(U){if(!m())break;if(!ue(U)&&!le(U)||w===t&&ue(U))throw U;v||=le(U),p||=ue(U),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let O=B.join(w,C.name),$=gR(t,O);if(O===n||O===a||ut(r,O)||ut(i,O)||e.denylist.some(U=>ut(U,O))||yt($)!==null)continue;if(!m())break;let de;try{de=await Z.lstat(O)}catch(U){if(!m())break;if(!ue(U)&&!le(U))throw U;if(v=!0,g({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:ue(U)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),h||!m())break;continue}if(!m())break;let ee=mR(de);if(ee==="directory"){if(bR(e.policy,$))continue;if(!m())break;let U;try{U=await Z.realpath(O)}catch(mt){if(!m())break;if(!ue(mt)&&!le(mt))throw mt;if(v=!0,g({path:$,type:ee}),s.push({path:$,size:null,type:"directory",reason:ue(mt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),h||!m())break;continue}if(!m())break;if(!F(e.physicalProjectRoot,U)||ut(e.physicalNativeRoot,U))continue;if(g({path:$,type:ee}),await e.hooks?.afterNode?.($),!m()||(await b(O),h))break;continue}if(g({path:$,type:ee}),await e.hooks?.afterNode?.($),!m()||h)break}}catch(C){k=!0,x=C}let N;try{await E.close()}catch(C){N=C}let y=m();if(k)throw x;if(y&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await b(t),m(),p?(o.length=0,d=0,f=0):(o.sort((w,E)=>w.path.localeCompare(E.path,"en")),s.sort((w,E)=>w.path.localeCompare(E.path,"en")));let S=p?X(`comet.native.physical-selection-incomplete.v1
151
+ `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=yv(o),c=sP(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function sP(e){let t=yv([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var Gx,Ux,Kx,Yx,Xx,Qx,Dt,ia,fv,pv,na=A(()=>{"use strict";Gr();pe();Gx="comet.native.acceptance.v1",Ux=/^acceptance-[a-f0-9]{64}$/u,Kx=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),Yx=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,Xx=/^[a-f0-9]{64}$/u,Qx=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;Dt=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ia=Object.freeze({maxCriteria:1024}),fv="<!-- comet-native:acceptance-evidence:start -->",pv="<!-- comet-native:acceptance-evidence:end -->"});var Hu=A(()=>{"use strict";na()});function Du(){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 $i,ss,bv,aa=A(()=>{"use strict";$i="comet.native.v4",ss="comet.native.local-execution.v4",bv=["multi-session","single-session"]});var Mu={};ep(Mu,{NativePortableStateVersionConflictError:()=>oa,appendNativePortableHistory:()=>Fu,compareAndSwapNativePortableState:()=>Cv,createNativePortableState:()=>Ev,parseNativePortableState:()=>_e,readNativePortableState:()=>Bt,writeNativePortableState:()=>qu});import{promises as cP}from"node:fs";function Ce(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xe(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ve(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 Lu(e,t){return e===null?null:ve(e,t)}function kv(e,t){let r=ve(e,t);if(!fP.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Oi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function re(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 hP(e,t){return e===null?null:re(e,t,Number.MIN_SAFE_INTEGER)}function ce(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Et(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function us(e,t){return Et(e,t,(r,i)=>ve(r,`${t}[${i}]`))}function Yr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Hi(e,t){let r=ve(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Vu(e,t,r=!1){let i=ve(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 ze(e,t){let r=Ce(e,t);return xe(r,new Set(["text","truncated"]),t),{text:ve(r.text,`${t}.text`,{empty:!0}),truncated:Oi(r.truncated,`${t}.truncated`)}}function mP(e,t){let r=`Native spec_changes[${t}]`,i=Ce(e,r);xe(i,new Set(["capability","operation","source"]),r);let n=ve(i.capability,`${r}.capability`);if(!uP.test(n))throw new Error(`${r}.capability is invalid`);let a=ce(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Vu(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 vP(e){let t="Native workspace",r=Ce(e,t);xe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ce(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Lu(r.change_branch,`${t}.change_branch`),a=Lu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ce(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 gP(e){let t="Native loop",r=Ce(e,t);xe(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=us(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Yr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ce(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ce(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:re(r.goal_cycle,`${t}.goal_cycle`,1),iteration:re(r.iteration,`${t}.iteration`),attempt:re(r.attempt,`${t}.attempt`),retry_epoch:re(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:re(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:re(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:re(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Lu(r.next_action,`${t}.next_action`)}}function wP(e,t){let r=`Native acceptance[${t}]`,i=Ce(e,r);xe(i,new Set(["id","source","text","result","reason"]),r);let n=ve(i.id,`${r}.id`);if(!dP.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Vu(i.source,`${r}.source`),text:ve(i.text,`${r}.text`),result:ce(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ze(i.reason,`${r}.reason`)}}function yP(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Ce(e,r);return xe(i,new Set(["name","result","note"]),r),{name:ze(i.name,`${r}.name`),result:ce(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ze(i.note,`${r}.note`)}}function NP(e){let t="Native builder_handoff",r=Ce(e,t);xe(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=us(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Yr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Ce(r.review,`${t}.review`);return n&&xe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ve(r.candidate_id,`${t}.candidate_id`),identity_provider:ve(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ve(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:re(r.iteration,`${t}.iteration`,1),summary:ze(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Et(r.checks,`${t}.checks`,yP),checks_truncated:Oi(r.checks_truncated,`${t}.checks_truncated`),known_limits:Et(r.known_limits,`${t}.known_limits`,(a,o)=>ze(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Oi(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ce(n.status,["passed"],`${t}.review.status`),summary:ze(n.summary,`${t}.review.summary`),reviewer_execution_ref:ve(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Hi(r.submitted_at,`${t}.submitted_at`)}}function bP(e,t){let r=`Native blockers[${t}]`,i=Ce(e,r);xe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=us(i.acceptance_ids,`${r}.acceptance_ids`);return Yr(n,`${r}.acceptance_ids`),{owner:ce(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ze(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ce(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function kP(e,t){let r=`Native verification.checks[${t}]`,i=Ce(e,r);return xe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ve(i.id,`${r}.id`),name:ze(i.name,`${r}.name`),argv_display:Et(i.argv_display,`${r}.argv_display`,(n,a)=>ze(n,`${r}.argv_display[${a}]`)),argv_truncated:Oi(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Vu(i.cwd_ref,`${r}.cwd_ref`,!0),status:ce(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:hP(i.exit_code,`${r}.exit_code`),duration_ms:re(i.duration_ms,`${r}.duration_ms`)}}function SP(e){let t="Native verification",r=Ce(e,t);xe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Et(r.checks,`${t}.checks`,kP);Yr(i.map(a=>a.id),`${t}.checks IDs`);let n=ve(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ve(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ve(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:re(r.iteration,`${t}.iteration`,1),attempt:re(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ce(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ce(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ze(r.summary,`${t}.summary`),risks:Et(r.risks,`${t}.risks`,(a,o)=>ze(a,`${t}.risks[${o}]`)),risks_truncated:Oi(r.risks_truncated,`${t}.risks_truncated`),completed_at:Hi(r.completed_at,`${t}.completed_at`)}}function Sv(e,t){let r=`Native history[${t}]`,i=Ce(e,r);xe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=us(i.unresolved_ids,`${r}.unresolved_ids`);return Yr(n,`${r}.unresolved_ids`),{goal_cycle:re(i.goal_cycle,`${r}.goal_cycle`,1),iteration:re(i.iteration,`${r}.iteration`),attempt:re(i.attempt,`${r}.attempt`),outcome:ce(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ze(i.summary,`${r}.summary`),completed_at:Hi(i.completed_at,`${r}.completed_at`)}}function EP(e){let t="Native history_overflow.outcome_counts",r=Ce(e,t),i=["pass","fail","blocked","execution-error","recovery"];return xe(r,new Set(i),t),{pass:re(r.pass,`${t}.pass`),fail:re(r.fail,`${t}.fail`),blocked:re(r.blocked,`${t}.blocked`),"execution-error":re(r["execution-error"],`${t}.execution-error`),recovery:re(r.recovery,`${t}.recovery`)}}function CP(e){let t="Native history_overflow",r=Ce(e,t);xe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=re(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Hi(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Hi(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=EP(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 xP(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 PP(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 _e(e){let t=Ce(e,"Native portable state");if(xe(t,pP,"Native portable state"),t.schema!==$i)throw new Error(`Native portable state schema must be ${$i}`);let r=ve(t.name,"Native state name");if(!lP.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=Et(t.spec_changes,"Native spec_changes",mP);Yr(i.map(s=>s.capability),"Native spec change capabilities");let n=Et(t.acceptance,"Native acceptance",wP);Yr(n.map(s=>s.id),"Native acceptance IDs");let a=Et(t.history,"Native history",Sv);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:$i,name:r,language:ce(t.language,["en","zh-CN"],"Native state language"),phase:ce(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ce(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:re(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:kv(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:kv(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ce(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:vP(t.workspace),loop:gP(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:NP(t.builder_handoff),blockers:Et(t.blockers,"Native blockers",bP),verification:t.verification===null?null:SP(t.verification),history:a,history_overflow:CP(t.history_overflow),verification_result:ce(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ce(t.verification_report,["verification.md"],"Native verification_report"),archived:Oi(t.archived,"Native archived"),created_at:Hi(t.created_at,"Native created_at")};return xP(o),PP(o),o}function Ev(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return _e({schema:$i,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:Du(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Fu(e,t){let r=_e(e),i=Sv(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return _e({...r,history:n,history_overflow:a})}function RP(e,t){let r=(0,ls.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 Bt(e){let t=await cP.readFile(e,"utf8");return _e(RP(t,"Native portable state"))}async function qu(e,t,r={}){let i=_e(t);await kt(e,(0,ls.stringify)(i),r)}async function AP(e,t){let r=cs.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);cs.set(e,a),await r;try{return await t()}finally{i(),cs.get(e)===a&&cs.delete(e)}}async function Cv(e){return AP(e.file,async()=>{let t=re(e.expectedStateVersion,"Native expected state version",1),r=_e(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Bt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new oa(t,i.state_version);return await qu(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Bt(e.file);if(n.state_version!==t)throw new oa(t,n.state_version)}}),r})}var ls,lP,uP,dP,fP,pP,oa,cs,yr=A(()=>{"use strict";ls=fi(Jr(),1);se();aa();lP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dP=/^A[1-9][0-9]*$/u,fP=/^[a-f0-9]{64}$/u,pP=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"]),oa=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};cs=new Map});var ds=A(()=>{"use strict"});var Nr,br,kr,Di,Bi,sa,fs=A(()=>{"use strict";Nr="comet.native.v3",br="comet.native.v2",kr="comet.native.v1",Di="comet.native.transition.v3",Bi="comet.native.transition.v2",sa="comet.native.transition.v1"});var Pv=A(()=>{"use strict";ge();Hu();yr();ds();aa();fs()});var Rv,VH,FH,Wu=A(()=>{"use strict";nt();Pv();Rv="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",VH=new RegExp(`^portable-archive-(${Rv})\\.json$`,"u"),FH=new RegExp(`^portable-migration-(${Rv})\\.json$`,"u")});import{createHash as _P}from"node:crypto";import{constants as ps,promises as He}from"node:fs";import st from"node:path";import{TextDecoder as IP}from"node:util";function ms(e,t){let r=st.relative(e,t);return r===""||!st.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${st.sep}`)}function Av(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function TP(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function jP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function hs(e,t){return W({...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 zu(e,t){let r=await He.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ju(e,t,r){let i=st.resolve(e),n=st.resolve(t);if(!ms(i,n))throw new Error(`${r} is outside its managed root`);let a=[await zu(i,r)],o=i;for(let s of st.relative(i,n).split(st.sep).filter(Boolean)){await Ct(a,r),o=st.join(o,s);let c=await zu(o,r);if(!ms(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ct(a,r),a}async function Ct(e,t){for(let r of e){let i=await He.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!TP(r,i)||await He.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function $P(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=Av(e.maxBytes),r=st.resolve(e.file),i=await Ju(e.root,st.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>zu(st.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ct(i,e.label);let a=await He.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=jP(a),s=await He.realpath(r);if(!ms(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ms(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ps.O_RDONLY:ps.O_RDONLY|ps.O_NOFOLLOW|ps.O_NONBLOCK,l=await He.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([He.lstat(r),He.realpath(r)]);if(await Ct(i,e.label),await Ct(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!hs(o,u)||!hs(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await $P(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),He.lstat(r),He.realpath(r)]);if(await Ct(i,e.label),await Ct(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!hs(o,v)||!hs(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:_P("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function _v(e){let t=await Lt(e),r;try{r=new IP("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 ca(e){let t=await Ju(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await He.readdir(e.directory,{withFileTypes:!0});else{let i=Av(e.maxEntries);r=[];let n=await He.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 Ct(t,e.label),{entries:r,verify:()=>Ct(t,e.label)}}async function Gu(e){let t=await Ju(e.root,e.directory,e.label);return{verify:()=>Ct(t,e.label)}}var ct=A(()=>{"use strict";se();bt()});import{TextDecoder as HP}from"util";var iD,nD,aD,oD,sD,vs=A(()=>{"use strict";se();Y();ct();iD=256*1024,nD=1024*1024,aD=16*1024,oD=64*1024*1024,sD=new HP("utf-8",{fatal:!0})});var lt=A(()=>{"use strict";We();ra();Wu();vs()});var Ov=A(()=>{"use strict"});import{createHash as Hv}from"crypto";import{createReadStream as BP}from"fs";async function Uu(e){let t=Hv("sha256");for await(let r of BP(e))t.update(r);return t.digest("hex")}function X(e){return Hv("sha256").update(e).digest("hex")}var xt=A(()=>{"use strict"});import{createHash as bs}from"crypto";import{spawn as zv}from"node:child_process";import{promises as Z}from"fs";import B from"path";function Gv(e){let t=e.deadlineMs??iR;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function ut(e){return Math.max(0,e.deadlineAt-Date.now())}function H(e){return ut(e)>=1}function Ku(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function Mi(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function sR(e){let t={...oR,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function cR(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&B.win32.isAbsolute(i)?B.win32.resolve(i):"C:\\Windows",a=B.win32.join(n,"System32","taskkill.exe");if(!B.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=zv(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),nR),u.unref()}catch{d(!1)}});for(let s=0;s<aR;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function rd(e,t,r,i){let n=ut(e);if(n<1)throw Ku();let a=e.gitProcess,o=zv(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=cR(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Ku(v.error):Ku()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Uv(e){let t={...td,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function ws(e,t,r,i=Qu){let{child:n,completion:a}=rd(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,i-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>i&&(u=!0)}),n.stderr.on("data",p=>{if(c>=zi)return;let v=zi-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Yu(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function ua(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=rd(e,t,r,i.stdin!==void 0),c=[],l=bs("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,g=!1,b=!1,S=w=>{let E=0;for(;E<w.byteLength;){let k=w.indexOf(0,E),x=k<0?w.byteLength:k,N=w.subarray(E,x);if(!m&&N.byteLength>0&&(h.byteLength+N.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),m=!0,g=!0):h=Buffer.concat([h,N])),k<0)break;v+=1,h.byteLength===0&&!m&&(b=!0);let y=h.byteLength+1;!m&&v<=i.maxRecords&&p+y<=i.maxBytes?(c.push(h),p+=y):g=!0,h=Buffer.alloc(0),m=!1,E=k+1}};o.stdout.on("data",w=>{l.update(w),f+=w.byteLength,f>i.maxBytes&&(g=!0);let E=i.outputChunkBytes;if(E===void 0){S(w);return}for(let k=0;k<w.byteLength;k+=E)S(w.subarray(k,Math.min(w.byteLength,k+E)))}),o.stderr.on("data",w=>{if(d>=zi)return;let E=zi-d,k=Buffer.from(w).subarray(0,E);u.push(k),d+=k.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:w,spawnError:E})=>{let k=i.acceptedExitCodes??[0];if(w!==null&&k.includes(w)&&E===null&&!b&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${E?`: ${E.message}`:b||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function ys(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function lR(e,t,r){if(r.length===0)return new Set;let i=await ua(e,t,["check-ignore","--no-index","-z","--stdin"],{...td,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=ys(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function uR(e,t,r){let{child:i,completion:n}=rd(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=zi)return;let d=zi-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Wi(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||B.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||B.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function dR(e,t){return e.map(r=>{let i=Wi(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function fR(e){let t=B.resolve(e);for(;;){try{return await Z.lstat(B.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=B.dirname(t);if(r===t)return!1;t=r}}async function Kv(e,t,r,i={}){let n=B.resolve(t.projectRoot),a=B.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=B.relative(n,B.resolve(f)).replaceAll("\\","/"),v=Wi(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},l=await ua(e,n,["ls-files","--stage","-z",...s],c);await i.afterStageBefore?.();let u=await ua(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await i.afterCombined?.();let d=await ua(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Yv(e){return{stageBefore:Yu(e.stagedBefore),combined:Yu(e.combined),stageAfter:Yu(e.stagedAfter)}}async function Xv(e,t,r=td,i={}){let n=B.resolve(t.projectRoot);if(!await fR(n))return null;let a;try{a=await ws(e,n,["rev-parse","--is-inside-work-tree"])}catch(b){throw Mi(b)?b:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:b})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await Kv(e,t,r,i)}catch(b){throw Mi(b)?b:new Error("Native Git snapshot provider failed after repository detection",{cause:b})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=b=>{for(let S of b){let w=ys(S),E=w.indexOf(" ");if(E<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(w.slice(0,E))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let x=Wi(w.slice(E+1));if(x===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(x),k.stage==="0"&&d.set(x,k.objectId),k.mode==="160000"&&k.stage==="0"&&f.add(x)}};p(s.records),p(l.records);let v=c.records.map(ys),h=dR(v,"combined"),m=new Set(h.filter(b=>!u.has(b))),g=new Set(h.filter((b,S)=>!u.has(b)&&v[S].endsWith("/")));for(let b of f)g.delete(b);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:Yv(o)}}function Cr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Dv(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function pR(e,t){return!Cr(e.stageBefore,e.stageAfter)||!Cr(e.stageAfter,t.stageBefore)||!Cr(e.combined,t.combined)||!Cr(t.stageBefore,t.stageAfter)}async function Qv(e,t,r,i,n){let a;try{a=await Kv(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Mi(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=i.initialFence,s=Yv(a),c=Dv(o)||Dv(s),l=pR(o,s);c&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(i.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:X(`comet.native.git-selection-overflow.v2
152
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}function mR(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Bv(e){let t=B.resolve(e.paths.projectRoot),r=B.resolve(e.paths.nativeRoot),i=B.resolve(e.paths.runtimeDir),n=B.resolve(e.paths.configFile),a=B.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>ut(e.execution)>=1?!0:(p=!0,h=!0,!1),g=w=>{let E=Buffer.from(`${w.type}\0${w.path}`,"utf8"),k=bs("sha256").update("comet.native.physical-selection-record.v1\0").update(E).digest();for(let x=0;x<c.length;x+=1)c[x]^=k[x];if(l=l+BigInt(`0x${k.toString("hex")}`)&hR,d+=1,f+=E.byteLength,Buffer.byteLength(w.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(w)},b=async w=>{if(h||!m())return;let E;try{E=await Z.opendir(w)}catch(C){if(!m())return;if(!ue(C)&&!le(C)||w===t&&ue(C))throw C;v||=le(C),p||=ue(C),h=!0;return}if(!m()){try{await E.close()}catch(C){if(C.code!=="ERR_DIR_CLOSED")throw C}return}let k=!1,x;try{for(;!h&&m();){let C;try{C=await E.read()}catch(U){if(!m())break;if(!ue(U)&&!le(U)||w===t&&ue(U))throw U;v||=le(U),p||=ue(U),h=!0;break}if(!m()||C===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let O=B.join(w,C.name),$=gR(t,O);if(O===n||O===a||dt(r,O)||dt(i,O)||e.denylist.some(U=>dt(U,O))||Nt($)!==null)continue;if(!m())break;let de;try{de=await Z.lstat(O)}catch(U){if(!m())break;if(!ue(U)&&!le(U))throw U;if(v=!0,g({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:ue(U)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),h||!m())break;continue}if(!m())break;let ee=mR(de);if(ee==="directory"){if(bR(e.policy,$))continue;if(!m())break;let U;try{U=await Z.realpath(O)}catch(vt){if(!m())break;if(!ue(vt)&&!le(vt))throw vt;if(v=!0,g({path:$,type:ee}),s.push({path:$,size:null,type:"directory",reason:ue(vt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),h||!m())break;continue}if(!m())break;if(!F(e.physicalProjectRoot,U)||dt(e.physicalNativeRoot,U))continue;if(g({path:$,type:ee}),await e.hooks?.afterNode?.($),!m()||(await b(O),h))break;continue}if(g({path:$,type:ee}),await e.hooks?.afterNode?.($),!m()||h)break}}catch(C){k=!0,x=C}let N;try{await E.close()}catch(C){N=C}let y=m();if(k)throw x;if(y&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await b(t),m(),p?(o.length=0,d=0,f=0):(o.sort((w,E)=>w.path.localeCompare(E.path,"en")),s.sort((w,E)=>w.path.localeCompare(E.path,"en")));let S=p?X(`comet.native.physical-selection-incomplete.v1
153
153
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):X(`comet.native.physical-selection.v1
154
- ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function Zv(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 vR(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Zv(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function eg(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function Lv(e,t){let i=(await ws(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Jv.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return X(`gitlink:${i}`)}async function Vv(e,t){let r=await Lv(e,t),i=await uR(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Lv(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function la(e,t){if(yt(t)!==null)return!1;let r=B.resolve(e.projectRoot,...t.split("/"));return!ut(B.resolve(e.nativeRoot),r)&&!ut(B.resolve(e.runtimeDir),r)}function gR(e,t){return B.relative(e,t).split(B.sep).join("/")}function wR(e,t){return t.map(r=>B.resolve(e,...r.split(/[\\/]/u)))}function ut(e,t){let r=B.resolve(e),i=B.resolve(t);return i===r||F(r,i)}function ue(e){return rR.has(e.code??"")}function le(e){return e.code==="ENOENT"}function id(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
154
+ ${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function Zv(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 vR(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Zv(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function eg(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function Lv(e,t){let i=(await ws(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Jv.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return X(`gitlink:${i}`)}async function Vv(e,t){let r=await Lv(e,t),i=await uR(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await Lv(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function la(e,t){if(Nt(t)!==null)return!1;let r=B.resolve(e.projectRoot,...t.split("/"));return!dt(B.resolve(e.nativeRoot),r)&&!dt(B.resolve(e.runtimeDir),r)}function gR(e,t){return B.relative(e,t).split(B.sep).join("/")}function wR(e,t){return t.map(r=>B.resolve(e,...r.split(/[\\/]/u)))}function dt(e,t){let r=B.resolve(e),i=B.resolve(t);return i===r||F(r,i)}function ue(e){return rR.has(e.code??"")}function le(e){return e.code==="ENOENT"}function id(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
155
155
  `)}function yR(e,t){return X(`comet.native.snapshot-policy.v1
156
156
  ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Xu(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 NR(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Fv(e){let t=as(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?NR(n):void 0;if(a&&!a())return!1;let o=Xu(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=Xu(r,c,a),o===null||o.size===0)return!1}return Xu(r,o,a)?.has(r.length)??!1}}function tg(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>as(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>as(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=yR(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(Fv),excludeMatchers:r.map(Fv),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 bR(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function qv(e,t,r){if(!e)return!0;let i=()=>H(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function da(e,t,r){let i=JSON.stringify(r);return X(`${e}
157
157
  ${Buffer.byteLength(t)}:${t}
158
- ${Buffer.byteLength(i)}:${i}`)}function Zu(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ns(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!Zu(r))return e.splice(t,1),r}return null}function Er(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kR(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await Z.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=bs("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Er(r,c))return{status:"changed"};for(;;){if(!H(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Er(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ge(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rg(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=B.posix.normalize(e);if(r!==e||B.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function SR(e,t){let r=Je(e,`Native snapshot entry ${t}`);Ge(r,YP,`Native snapshot entry ${t}`);let i=rg(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!ks.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:xt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Jv.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function ER(e,t){let r=Je(e,`Native snapshot omission ${t}`);if(Ge(r,XP,`Native snapshot omission ${t}`),!eR.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!tR.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:rg(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:xt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function CR(e){let t=Je(e,"Native snapshot omission overflow");if(Ge(t,QP,"Native snapshot omission overflow"),typeof t.hash!="string"||!ks.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:qi(t.count,"Native snapshot omission overflow count")}}function Fi(e,t){let r=Je(e,t);if(Ge(r,GP,t),typeof r.hash!="string"||!ks.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=xt(r.recordCount,`${t} recordCount`),n=xt(r.storedRecordCount,`${t} storedRecordCount`),a=xt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Mv(e){let t=Je(e,"Native Git selection evidence");if(Ge(t,JP,"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=Fi(t.stageBefore,"Native Git selection stageBefore"),i=Fi(t.combined,"Native Git selection combined"),n=Fi(t.stageAfter,"Native Git selection stageAfter"),a=Fi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Fi(t.finalCombined,"Native Git selection finalCombined"),s=Fi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Cr(r,n)||!Cr(n,a)||!Cr(i,o)||!Cr(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 Wv(e,t){let r=Je(e,t);if(Ge(r,KP,t),typeof r.hash!="string"||!ks.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=xt(r.visitedNodeCount,`${t} visitedNodeCount`),n=xt(r.recordCount,`${t} recordCount`),a=xt(r.storedRecordCount,`${t} storedRecordCount`),o=xt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function xR(e){let t=Je(e,"Native physical selection evidence");if(Ge(t,UP,"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=Wv(t.before,"Native physical selection before"),i=Wv(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Zv(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 Xr(e){let t=Je(e,"Native content snapshot manifest");if(Ge(t,FP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ZP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let k=Je(t.capture,"Native content snapshot capture");if(Ge(k,WP,"Native content snapshot capture"),k.provider!=="git"&&k.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=k.gitSelection===void 0?void 0:Mv(k.gitSelection),N=k.physicalSelection===void 0?void 0:xR(k.physicalSelection),y=null;if(k.projection!==void 0){let C=Je(k.projection,"Native content snapshot projection");if(Ge(C,zP,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:Mv(C.selection)}}}if(k.provider==="git"){if(N||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}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=Je(t.limits,"Native content snapshot limits");Ge(i,qP,"Native content snapshot limits");let n={maxFiles:qi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:qi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:qi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:qi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:qi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let k=Je(t.policy,"Native snapshot policy");if(Ge(k,MP,"Native snapshot policy"),k.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(k.include)||!Array.isArray(k.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=tg({include:k.include,exclude:k.exclude,hash:k.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(SR),s=t.omitted.map(ER),c=xt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:CR(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(k=>k.size>n.maxFileBytes)||o.reduce((k,x)=>k+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(k=>k.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>ed||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(k=>k.reason==="git-enumeration-limit"),f=s.filter(k=>k.reason==="git-selection-changed");for(let k of[...d,...f])if(k.path!=="."||k.size!==null||k.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(k=>k.reason==="physical-enumeration-limit"),g=s.filter(k=>k.reason==="physical-selection-changed");for(let k of[...m,...g])if(k.path!=="."||k.size!==null||k.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",w=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(w!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={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(id(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function ig(e,t,r={}){let i=Xr(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=B.resolve(e.projectRoot),a=Gv(r),o=Uv(r.gitSelectionLimits),s=await Xv(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(eg(s).filter(N=>la(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>la(e,N)),d=(N,y)=>y.some(C=>N===C||N.startsWith(`${C}/`)),f=N=>d(N,l),p=N=>d(N,u),v=[...i.entries.map(N=>N.path),...i.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!p(N)),h=await lR(a,n,v),m=i.entries.filter(N=>!f(N.path)&&!p(N.path)&&la(e,N.path)&&(c.has(N.path)||!h.has(N.path)));await Qv(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let N of l)g.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((N,y)=>N.path.localeCompare(y.path,"en"));let b=i.omitted.filter(N=>f(N.path)||p(N.path)||!la(e,N.path)?!1:h.has(N.path)?c.has(N.path)||[...c].some(y=>y.startsWith(`${N.path}/`)):!0);for(let N of g)b.some(y=>y.path===N.path&&y.reason===N.reason)||b.push(N);b.sort((N,y)=>N.path.localeCompare(y.path,"en"));let S=i.omissionOverflow?.count??0,w=i.omissionOverflow?.hash??X("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,w=da(w,"git-selection",{source:"git-selection",...s.overflow}));let E=N=>{S+=1,w=da(w,"omission",N)};for(;b.length>ed;){let N=Ns(b);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(N)}let k=()=>({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+S===0,entries:m,omitted:b,omittedCount:b.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${w}`,hash:w,count:S}}:{}}),x=k();for(;id(x)>i.limits.maxManifestBytes;){let N=Ns(b);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(N),x=k()}return Xr(x)}function PR(e,t){if(!VP.test(t))throw new Error(`Invalid Native change name: ${t}`);return B.join(K(e,t),"baseline-manifest.json")}async function ng(e,t={}){let r={maxFiles:t.limits?.maxFiles??gs.maxFiles,maxFileBytes:t.limits?.maxFileBytes??gs.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??gs.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??gs.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=tg(t.policy),n=Gv({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Uv(t.gitSelectionLimits),o=sR(t.physicalSelectionLimits);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=B.resolve(e.projectRoot),c=await Z.realpath(s),l=B.resolve(e.nativeRoot),u=await Z.realpath(l),d=B.resolve(e.runtimeDir),f=B.resolve(e.configFile),p=B.join(s,".comet","current-change.json"),v=wR(s,t.denylist??[]),h=[],m=[],g=new Map,b=new Map,S=0,w=0,E=X("comet.native.snapshot-omission-overflow.v1"),k=0,x=!1,N=null,y=I=>{w+=1,E=da(E,"omission",I)},C=I=>{if(S+=1,m.length<ed){m.push(I);return}if(Zu(I)){let _=Ns(m);if(_===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(_),m.push(I);return}y(I)},O=I=>{S+=I.count,w+=I.count,E=da(E,"git-selection",{source:"git-selection",...I})},$=I=>{w+=1,E=da(E,"manifest-entry",{reason:"manifest-size",entry:I})},de=async(I,_)=>{h.push(I),k+=I.size,g.set(I.path,_),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(I.path))},ee=(I,_)=>{let T=h.findIndex(Q=>Q.path===I);if(T<0)return;let[L]=h.splice(T,1);k-=L.size,g.delete(I),C(_)},U=async(I,_,T,L)=>{if(!T.isFile()||T.isSymbolicLink()||!H(n))return;let Q;try{Q=await Z.realpath(I)}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;C({path:_,size:T.size,type:"file",reason:le(R)?"changed-during-read":"unreadable"});return}if(!H(n)||!F(c,Q)||ut(u,Q))return;if(h.length>=r.maxFiles){C({path:_,size:T.size,type:"file",reason:"file-count"});return}if(T.size>r.maxFileBytes){C({path:_,size:T.size,type:"file",reason:"file-size"});return}if(k+T.size>r.maxTotalBytes){C({path:_,size:T.size,type:"file",reason:"total-size"});return}let M,D,ie;try{if(M=await kR(Q,T.size,T,n),M.status==="budget-exhausted"||!H(n))return;if(M.status==="changed"){C({path:_,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(ie=await Z.realpath(I),!H(n)))return;D=await Z.lstat(I)}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;C({path:_,size:T.size,type:"file",reason:le(R)?"changed-during-read":"unreadable"});return}if(H(n)){if(M.bytes!==T.size||ie!==Q||!Er(T,M.finalStat)||!Er(M.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==T.size||D.mtimeMs!==T.mtimeMs||D.ctimeMs!==T.ctimeMs){C({path:_,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await de({path:_,hash:M.hash,size:D.size,type:"file",...L===void 0?{}:{gitObjectId:L}},{kind:"file",target:I,realTarget:Q,stat:D})}},mt=async(I,_,T)=>{if(!H(n))return;let L,Q,M;try{if(L=await Z.readlink(I,{encoding:"buffer"}),!H(n)||(M=await Z.lstat(I),!H(n)))return;Q=await Z.readlink(I,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;C({path:_,size:null,type:"other",reason:le(R)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!M.isSymbolicLink()||!Er(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!L.equals(Q)){C({path:_,size:null,type:"other",reason:"changed-during-read"});return}let D=L.byteLength;if(h.length>=r.maxFiles){C({path:_,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:_,size:D,type:"other",reason:"file-size"});return}if(k+D>r.maxTotalBytes){C({path:_,size:D,type:"other",reason:"total-size"});return}let ie=bs("sha256").update("symlink\0").update(L).digest("hex");H(n)&&await de({path:_,hash:ie,size:D,type:"file"},{kind:"symlink",target:I,rawTarget:L,stat:M})},Qe=async()=>{for(let[I,_]of[...g]){if(!H(n))return;if(_.kind==="file"){let D,ie;try{if(D=await Z.realpath(_.target),!H(n))return;ie=await Z.lstat(_.target)}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;ee(I,{path:I,size:null,type:"file",reason:ue(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==_.realTarget||!ie.isFile()||ie.isSymbolicLink()||!Er(_.stat,ie)||ie.size!==_.stat.size||ie.mtimeMs!==_.stat.mtimeMs||ie.ctimeMs!==_.stat.ctimeMs)&&ee(I,{path:I,size:ie.isFile()?ie.size:null,type:ie.isFile()?"file":"other",reason:"changed-during-read"});continue}if(_.kind==="symlink"){let D,ie;try{if(D=await Z.lstat(_.target),!H(n))return;ie=await Z.readlink(_.target,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;ee(I,{path:I,size:null,type:"other",reason:ue(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Er(_.stat,D)||D.mtimeMs!==_.stat.mtimeMs||D.ctimeMs!==_.stat.ctimeMs||!_.rawTarget.equals(ie))&&ee(I,{path:I,size:null,type:"other",reason:"changed-during-read"});continue}let T,L;try{if(T=await Z.realpath(_.target),!H(n))return;L=await Z.lstat(_.target)}catch{if(!H(n))return;ee(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!(T===_.realTarget&&L.isDirectory()&&!L.isSymbolicLink()&&Er(_.stat,L)&&F(c,T)&&!ut(u,T))){ee(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!H(n))return;M=await Vv(n,T)}catch(D){if(Mi(D))throw D;ee(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;M.dirty?ee(I,{path:I,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==_.hash&&ee(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"})}for(let[I,_]of b){if(!H(n))return;try{let T=await Z.lstat(_);if(!H(n))return;C({path:I,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!H(n))return;if(le(T))continue;if(!ue(T))throw T;C({path:I,size:null,type:"file",reason:"unreadable"})}}},$e=await Xv(n,e,a,t.gitSelectionHooks);if($e===null){let I=await Bv({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let L of I.records){if(L.type!=="file"&&L.type!=="symlink"||g.has(L.path))continue;if(lt(n)<1)break;if(!qv(i,L.path,n))continue;if(lt(n)<1)break;let Q=B.resolve(s,...L.path.split("/")),M;try{M=await Z.lstat(Q)}catch(D){if(!H(n))break;if(!ue(D)&&!le(D))throw D;C({path:L.path,size:null,type:"file",reason:le(D)?"changed-during-read":"unreadable"});continue}if(lt(n)<1)break;if(L.type==="symlink"&&M.isSymbolicLink()){if(await mt(Q,L.path,M),lt(n)<1)break;continue}if(L.type!=="file"||!M.isFile()||M.isSymbolicLink()){C({path:L.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await U(Q,L.path,M),lt(n)<1)break}lt(n)>=1&&await Qe();let _=await Bv({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o}),T=vR(I.evidence,_.evidence);N=T.evidence;for(let L of[...I.omissions,..._.omissions,...T.omissions])m.some(Q=>Q.path===L.path&&Q.reason===L.reason)||C(L)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let I=t.incrementalBaseline,_=new Map,T=!1;if(I){let R=Xr(I);for(let te of R.entries)te.gitObjectId!==void 0&&_.set(te.path,te);T=_.size>0}let L=new Set,Q=!0;try{let R=await ua(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)T=!1,Q=!1,_.clear();else for(let te of R.records){let ne=ys(te),Se=ne.indexOf(" "),Ne=Se<0?null:Wi(ne.slice(Se+1));if(Se!==1||Ne===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ne[0]!=="H"&&L.add(Ne)}}catch(R){if(Mi(R))throw R;T=!1,Q=!1,_.clear()}let M=new Set;try{let R=await ws(n,s,["ls-files","--modified","-z"],Qu);for(let te of R.toString("utf8").split("\0")){let ne=Wi(te);ne!==null&&M.add(ne)}}catch{T=!1,Q=!1,_.clear()}let D=new Set,ie=new Set;for(let R of eg($e)){if(g.has(R)||!la(e,R))continue;if(lt(n)<1)break;if(!qv(i,R,n))continue;if(lt(n)<1)break;let te=B.resolve(s,...R.split("/"));if(te===f||te===p||ut(d,te)||v.some(Oe=>ut(Oe,te)))continue;if($e.gitlinks.has(R)){if(h.length>=r.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Oe,Wa;try{[Oe,Wa]=await Promise.all([Z.realpath(te),Z.lstat(te)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wa.isSymbolicLink()||!Wa.isDirectory()||!F(c,Oe)||ut(u,Oe)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let di=await Vv(n,Oe);if(di.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await de({path:R,hash:di.hash,size:0,type:"file"},{kind:"gitlink",target:te,realTarget:Oe,stat:Wa,hash:di.hash})}catch(di){if(Mi(di))throw di;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ne;try{ne=await Z.lstat(te)}catch(Oe){if(le(Oe)&&$e.tracked.has(R)){b.set(R,te);continue}if(!ue(Oe)&&!le(Oe))throw Oe;C({path:R,size:null,type:"file",reason:le(Oe)?"changed-during-read":"unreadable"});continue}if(ne.isSymbolicLink()){await mt(te,R,ne);continue}if(!ne.isFile()){$e.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let Se=$e.trackedObjectIds.get(R),Ne=Se?_.get(R):void 0;if(T&&Ne?.gitObjectId!==void 0&&Ne.gitObjectId===Se&&!L.has(R)&&!M.has(R)){if(h.length>=r.maxFiles){C({path:R,size:Ne.size,type:"file",reason:"file-count"});continue}if(Ne.size>r.maxFileBytes){C({path:R,size:Ne.size,type:"file",reason:"file-size"});continue}if(k+Ne.size>r.maxTotalBytes){C({path:R,size:Ne.size,type:"file",reason:"total-size"});continue}h.push({...Ne}),k+=Ne.size,D.add(R);continue}let Zf=Q&&!L.has(R)&&!M.has(R)?Se:void 0;await U(te,R,ne,Zf),Zf!==void 0&&ie.add(R)}if(await Qe(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Qv(n,e,a,$e,t.gitSelectionHooks?.outputChunkBytes),D.size>0||T&&ie.size>0){let R=await ws(n,s,["ls-files","--modified","-z"],Qu),te=new Set;for(let ne of R.toString("utf8").split("\0")){let Se=Wi(ne);Se!==null&&te.add(Se)}for(let ne of D){if(!te.has(ne))continue;let Se=h.find(Ne=>Ne.path===ne);ee(ne,{path:ne,size:Se?.size??null,type:"file",reason:"changed-during-read"})}for(let ne of ie){if(!te.has(ne))continue;let Se=h.find(Ne=>Ne.path===ne);Se&&delete Se.gitObjectId}}for(let R of $e.omissions)C(R);$e.overflow&&O($e.overflow)}h.sort((I,_)=>I.path.localeCompare(_.path,"en")),m.sort((I,_)=>I.path.localeCompare(_.path,"en"));let cb=$e===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...$e.evidence?{gitSelection:$e.evidence}:{}},Qf=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:cb,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:m,omittedCount:S,...w>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:w}}:{}}),Ec=Qf();for(;id(Ec)>r.maxManifestBytes;){if(m.filter(_=>!Zu(_)).length>0){let _=Math.max(1,Math.ceil(m.length/4));for(let T=0;T<_;T+=1){let L=Ns(m);if(L===null)break;y(L)}}else if(h.length>0){let _=Math.max(1,Math.ceil(h.length/4));for(let T of h.splice(-_))S+=1,$(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ec=Qf()}return Ec}async function nd(e,t,r={}){let n=(await Ae(e.projectRoot))?.native.snapshot??Au;return ng(e,{...r,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Ss(e,t){let r=PR(e,t),i=me(e,r);await G(i,r);try{let n=await _v({root:i,file:r,maxBytes:LP,label:"Native baseline snapshot manifest"});return Xr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var gs,ed,LP,VP,FP,qP,MP,WP,zP,JP,GP,UP,KP,YP,XP,QP,ZP,eR,tR,ks,Jv,rR,zi,Qu,iR,nR,aR,td,oR,hR,Ji=A(()=>{"use strict";se();We();Ct();Nt();Y();st();Gn();gs={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},ed=1e3,LP=8*1024*1024,VP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),qP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),MP=new Set(["schema","include","exclude","hash"]),WP=new Set(["provider","gitSelection","physicalSelection","projection"]),zP=new Set(["provider","selection"]),JP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),GP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),UP=new Set(["schema","status","before","after"]),KP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),YP=new Set(["path","hash","size","type","gitObjectId"]),XP=new Set(["path","size","type","reason"]),QP=new Set(["ref","hash","count"]),ZP=new Set(["change-created","legacy-migration","explicit"]),eR=new Set(["file","directory","other"]),tR=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"]),ks=/^[a-f0-9]{64}$/u,Jv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,rR=new Set(["EACCES","EPERM"]),zi=64*1024,Qu=64*1024,iR=6e4,nR=1e3,aR=2,td={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},oR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};hR=(1n<<256n)-1n});var Ue,Gi=A(()=>{"use strict";Ue=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"})});var Es=A(()=>{"use strict"});var ag=A(()=>{"use strict"});var ad=A(()=>{"use strict";Es()});var og=A(()=>{"use strict";Es();ad()});var jR,sg=A(()=>{"use strict";jR=fi(Jr(),1);_i();pr();Kr()});var UD,cg=A(()=>{"use strict";_i();Kr();UD=4*1024*1024});function OR(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function lg(e,t){return(...r)=>{let i=$R;if(i===null)return t(...r);let n=OR(`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 $R,ug=A(()=>{"use strict";$R=null});var ZD,dg=A(()=>{"use strict";ug();Ai();ZD=lg("hookWritePolicy",async e=>(await wu(e))?.hook??{allow_paths:[]})});var fg=A(()=>{"use strict";Es();_i();ag();og();pr();sg();Kr();Ai();ku();cg();dg();yu();ad()});var pg=A(()=>{"use strict";fg();Un()});import DR from"path";function pa(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function fa(e,t){let r=pa(e,t);if(DR.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function BR(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function mg(e){if(!e.run_id)return null;let t=pa(e,"run_id"),r=pa(e,"skill"),i=pa(e,"skill_version"),n=pa(e,"skill_hash"),a=fa(e,"pending_ref"),o=fa(e,"trajectory_ref"),s=fa(e,"context_ref"),c=fa(e,"artifacts_ref"),l=fa(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:hg(e,"current_step"),iteration:u,pending:hg(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:BR(e)}}var hg,XB,vg=A(()=>{"use strict";pg();hg=(e,t)=>{let r=e[t];return r==null?null:String(r)};XB=256*1024});function VR(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=mg(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function od(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!LR.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return VR(t)}var LR,gg=A(()=>{"use strict";vg();Gi();LR=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{constants as Cs,promises as dt}from"node:fs";import ft from"node:path";import{TextDecoder as FR}from"node:util";function Ps(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}function qR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xs(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function MR(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Rs(e,t,r){let i=Ue[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=ft.resolve(e),a=ft.resolve(n,...i.slice(8).split("/"));if(!Ps(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function wg(e){let t=await dt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await dt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function WR(e,t){let r=ft.resolve(e),i=ft.resolve(t);if(!Ps(r,i))throw new Error("Native Run path is outside its change");let n=[await wg(r)],a=r;for(let o of ft.relative(r,i).split(ft.sep).filter(Boolean)){a=ft.join(a,o);let s;try{s=await wg(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ps(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function yg(e){for(let t of e){let r=await dt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!MR(t,r)||await dt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function zR(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 As(e,t,r,i,n){let a=await WR(e,ft.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await dt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=qR(o),c=await dt.realpath(t);if(!Ps(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Cs.O_RDONLY:Cs.O_RDONLY|Cs.O_NOFOLLOW|Cs.O_NONBLOCK,u;try{u=await dt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),dt.lstat(t),dt.realpath(t)]);if(await yg(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!xs(s,d)||!xs(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let v=await zR(u,r,i);await n?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([u.stat(),dt.lstat(t),dt.realpath(t)]);if(await yg(a),!m.isFile()||m.isSymbolicLink()||g!==c||!xs(s,h)||!xs(s,m))throw new Error(`${i} changed while reading`);let b;try{b=new FR("utf-8",{fatal:!0}).decode(v)}catch(S){throw new Error(`${i} is not valid UTF-8`,{cause:S})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Ng(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function sd(e){return od(e)}async function Ki(e,t){let r=Rs(e,"stateRef"),i=await As(e,r,Ui.runStateBytes,"Native Run state",t);return i?od(Ng(i.text,"Native Run state")):null}async function Qr(e,t,r){let i=Rs(e,"trajectoryRef",t),n=await As(e,i,Ui.trajectoryBytes,"Native Run trajectory",r);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ui.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ui.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function bg(e,t,r){return(await As(e,Rs(e,"trajectoryRef",t),Ui.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function _s(e,t,r){let i=await As(e,Rs(e,"checkpointRef",t),Ui.checkpointBytes,"Native Run checkpoint",r);return i?Ng(i.text,"Native Run checkpoint"):null}var Ui,Zr=A(()=>{"use strict";Gi();gg();se();Nt();Ui={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});import{createHash as JR}from"crypto";import GR from"path";function cd(e){return JR("sha256").update(e).digest("hex")}function KR(e,t){if(!UR.test(t))throw new Error(`Invalid Native change name: ${t}`);return GR.join(K(e,t),"trajectory.jsonl")}function YR(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function XR(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function QR(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=YR(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
159
- `)])}catch(d){if(!XR(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:cd(t),targetHash:cd(l),tailHash:cd(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function ZR(e,t){let r=KR(e,t);await G(me(e,r),r);let i=K(e,t),n=await bg(i,Ue.trajectoryRef);return n===null?{status:"clean",file:r}:QR(r,Buffer.from(n))}async function kg(e,t){let r=await ZR(e,t);return"inspection"in r?r.inspection:r}var UR,Is=A(()=>{"use strict";Gi();ct();Y();Zr();UR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as eA}from"node:crypto";import{promises as Ts}from"node:fs";import Vt from"node:path";function Yi(e){return rA.has(e)}function Pg(e,t){let r=Vt.relative(e,t);return Vt.isAbsolute(r)||r===".."||r.startsWith(`..${Vt.sep}`)?null:r.replaceAll("\\","/")||"."}function Rg(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Ag(e,t){if(e.length===0||Rg(e)||e.includes("\\")||Vt.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=Vt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function dd(e,t){return eA("sha256").update(`${e}
160
- ${t}`).digest("hex")}async function Eg(e,t){let r=await Ts.realpath(t),i=await Ts.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ud==="win32"?Vt.normalize(r).toLowerCase():r;return dd(e,`${n}
158
+ ${Buffer.byteLength(i)}:${i}`)}function Zu(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Ns(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!Zu(r))return e.splice(t,1),r}return null}function Er(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kR(e,t,r,i){if(!H(i))return{status:"budget-exhausted"};let n;try{n=await Z.open(e,"r")}catch(c){if(!H(i))return{status:"budget-exhausted"};throw c}if(!H(i))return await n.close(),{status:"budget-exhausted"};let a=bs("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!H(i))return{status:"budget-exhausted"};let c=await n.stat();if(!H(i))return{status:"budget-exhausted"};if(!c.isFile()||!Er(r,c))return{status:"changed"};for(;;){if(!H(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!H(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!H(i))return{status:"budget-exhausted"};let d=await n.stat();return H(i)?!d.isFile()||!Er(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Je(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ge(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Pt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rg(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=B.posix.normalize(e);if(r!==e||B.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function SR(e,t){let r=Je(e,`Native snapshot entry ${t}`);Ge(r,YP,`Native snapshot entry ${t}`);let i=rg(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!ks.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:Pt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Jv.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function ER(e,t){let r=Je(e,`Native snapshot omission ${t}`);if(Ge(r,XP,`Native snapshot omission ${t}`),!eR.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!tR.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:rg(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Pt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function CR(e){let t=Je(e,"Native snapshot omission overflow");if(Ge(t,QP,"Native snapshot omission overflow"),typeof t.hash!="string"||!ks.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:qi(t.count,"Native snapshot omission overflow count")}}function Fi(e,t){let r=Je(e,t);if(Ge(r,GP,t),typeof r.hash!="string"||!ks.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=Pt(r.recordCount,`${t} recordCount`),n=Pt(r.storedRecordCount,`${t} storedRecordCount`),a=Pt(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 Mv(e){let t=Je(e,"Native Git selection evidence");if(Ge(t,JP,"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=Fi(t.stageBefore,"Native Git selection stageBefore"),i=Fi(t.combined,"Native Git selection combined"),n=Fi(t.stageAfter,"Native Git selection stageAfter"),a=Fi(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Fi(t.finalCombined,"Native Git selection finalCombined"),s=Fi(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Cr(r,n)||!Cr(n,a)||!Cr(i,o)||!Cr(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 Wv(e,t){let r=Je(e,t);if(Ge(r,KP,t),typeof r.hash!="string"||!ks.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=Pt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Pt(r.recordCount,`${t} recordCount`),a=Pt(r.storedRecordCount,`${t} storedRecordCount`),o=Pt(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 xR(e){let t=Je(e,"Native physical selection evidence");if(Ge(t,UP,"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=Wv(t.before,"Native physical selection before"),i=Wv(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Zv(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 Xr(e){let t=Je(e,"Native content snapshot manifest");if(Ge(t,FP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!ZP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let k=Je(t.capture,"Native content snapshot capture");if(Ge(k,WP,"Native content snapshot capture"),k.provider!=="git"&&k.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=k.gitSelection===void 0?void 0:Mv(k.gitSelection),N=k.physicalSelection===void 0?void 0:xR(k.physicalSelection),y=null;if(k.projection!==void 0){let C=Je(k.projection,"Native content snapshot projection");if(Ge(C,zP,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...C.selection===void 0?{}:{selection:Mv(C.selection)}}}if(k.provider==="git"){if(N||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}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=Je(t.limits,"Native content snapshot limits");Ge(i,qP,"Native content snapshot limits");let n={maxFiles:qi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:qi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:qi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:qi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:qi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let k=Je(t.policy,"Native snapshot policy");if(Ge(k,MP,"Native snapshot policy"),k.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(k.include)||!Array.isArray(k.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=tg({include:k.include,exclude:k.exclude,hash:k.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(SR),s=t.omitted.map(ER),c=Pt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:CR(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(k=>k.size>n.maxFileBytes)||o.reduce((k,x)=>k+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(k=>k.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>ed||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(k=>k.reason==="git-enumeration-limit"),f=s.filter(k=>k.reason==="git-selection-changed");for(let k of[...d,...f])if(k.path!=="."||k.size!==null||k.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(k=>k.reason==="physical-enumeration-limit"),g=s.filter(k=>k.reason==="physical-selection-changed");for(let k of[...m,...g])if(k.path!=="."||k.size!==null||k.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",w=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(w!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={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(id(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}async function ig(e,t,r={}){let i=Xr(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=B.resolve(e.projectRoot),a=Gv(r),o=Uv(r.gitSelectionLimits),s=await Xv(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(eg(s).filter(N=>la(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>la(e,N)),d=(N,y)=>y.some(C=>N===C||N.startsWith(`${C}/`)),f=N=>d(N,l),p=N=>d(N,u),v=[...i.entries.map(N=>N.path),...i.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!p(N)),h=await lR(a,n,v),m=i.entries.filter(N=>!f(N.path)&&!p(N.path)&&la(e,N.path)&&(c.has(N.path)||!h.has(N.path)));await Qv(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let N of l)g.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((N,y)=>N.path.localeCompare(y.path,"en"));let b=i.omitted.filter(N=>f(N.path)||p(N.path)||!la(e,N.path)?!1:h.has(N.path)?c.has(N.path)||[...c].some(y=>y.startsWith(`${N.path}/`)):!0);for(let N of g)b.some(y=>y.path===N.path&&y.reason===N.reason)||b.push(N);b.sort((N,y)=>N.path.localeCompare(y.path,"en"));let S=i.omissionOverflow?.count??0,w=i.omissionOverflow?.hash??X("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,w=da(w,"git-selection",{source:"git-selection",...s.overflow}));let E=N=>{S+=1,w=da(w,"omission",N)};for(;b.length>ed;){let N=Ns(b);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");E(N)}let k=()=>({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+S===0,entries:m,omitted:b,omittedCount:b.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${w}`,hash:w,count:S}}:{}}),x=k();for(;id(x)>i.limits.maxManifestBytes;){let N=Ns(b);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");E(N),x=k()}return Xr(x)}function PR(e,t){if(!VP.test(t))throw new Error(`Invalid Native change name: ${t}`);return B.join(K(e,t),"baseline-manifest.json")}async function ng(e,t={}){let r={maxFiles:t.limits?.maxFiles??gs.maxFiles,maxFileBytes:t.limits?.maxFileBytes??gs.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??gs.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??gs.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=tg(t.policy),n=Gv({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Uv(t.gitSelectionLimits),o=sR(t.physicalSelectionLimits);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=B.resolve(e.projectRoot),c=await Z.realpath(s),l=B.resolve(e.nativeRoot),u=await Z.realpath(l),d=B.resolve(e.runtimeDir),f=B.resolve(e.configFile),p=B.join(s,".comet","current-change.json"),v=wR(s,t.denylist??[]),h=[],m=[],g=new Map,b=new Map,S=0,w=0,E=X("comet.native.snapshot-omission-overflow.v1"),k=0,x=!1,N=null,y=I=>{w+=1,E=da(E,"omission",I)},C=I=>{if(S+=1,m.length<ed){m.push(I);return}if(Zu(I)){let _=Ns(m);if(_===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(_),m.push(I);return}y(I)},O=I=>{S+=I.count,w+=I.count,E=da(E,"git-selection",{source:"git-selection",...I})},$=I=>{w+=1,E=da(E,"manifest-entry",{reason:"manifest-size",entry:I})},de=async(I,_)=>{h.push(I),k+=I.size,g.set(I.path,_),x||(x=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(I.path))},ee=(I,_)=>{let T=h.findIndex(Q=>Q.path===I);if(T<0)return;let[L]=h.splice(T,1);k-=L.size,g.delete(I),C(_)},U=async(I,_,T,L)=>{if(!T.isFile()||T.isSymbolicLink()||!H(n))return;let Q;try{Q=await Z.realpath(I)}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;C({path:_,size:T.size,type:"file",reason:le(R)?"changed-during-read":"unreadable"});return}if(!H(n)||!F(c,Q)||dt(u,Q))return;if(h.length>=r.maxFiles){C({path:_,size:T.size,type:"file",reason:"file-count"});return}if(T.size>r.maxFileBytes){C({path:_,size:T.size,type:"file",reason:"file-size"});return}if(k+T.size>r.maxTotalBytes){C({path:_,size:T.size,type:"file",reason:"total-size"});return}let M,D,ie;try{if(M=await kR(Q,T.size,T,n),M.status==="budget-exhausted"||!H(n))return;if(M.status==="changed"){C({path:_,size:null,type:"file",reason:"changed-during-read"});return}if(!H(n)||(ie=await Z.realpath(I),!H(n)))return;D=await Z.lstat(I)}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;C({path:_,size:T.size,type:"file",reason:le(R)?"changed-during-read":"unreadable"});return}if(H(n)){if(M.bytes!==T.size||ie!==Q||!Er(T,M.finalStat)||!Er(M.finalStat,D)||!D.isFile()||D.isSymbolicLink()||D.size!==T.size||D.mtimeMs!==T.mtimeMs||D.ctimeMs!==T.ctimeMs){C({path:_,size:D.isFile()?D.size:null,type:D.isFile()?"file":"other",reason:"changed-during-read"});return}H(n)&&await de({path:_,hash:M.hash,size:D.size,type:"file",...L===void 0?{}:{gitObjectId:L}},{kind:"file",target:I,realTarget:Q,stat:D})}},vt=async(I,_,T)=>{if(!H(n))return;let L,Q,M;try{if(L=await Z.readlink(I,{encoding:"buffer"}),!H(n)||(M=await Z.lstat(I),!H(n)))return;Q=await Z.readlink(I,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;C({path:_,size:null,type:"other",reason:le(R)?"changed-during-read":"unreadable"});return}if(!H(n))return;if(!M.isSymbolicLink()||!Er(T,M)||M.mtimeMs!==T.mtimeMs||M.ctimeMs!==T.ctimeMs||!L.equals(Q)){C({path:_,size:null,type:"other",reason:"changed-during-read"});return}let D=L.byteLength;if(h.length>=r.maxFiles){C({path:_,size:D,type:"other",reason:"file-count"});return}if(D>r.maxFileBytes){C({path:_,size:D,type:"other",reason:"file-size"});return}if(k+D>r.maxTotalBytes){C({path:_,size:D,type:"other",reason:"total-size"});return}let ie=bs("sha256").update("symlink\0").update(L).digest("hex");H(n)&&await de({path:_,hash:ie,size:D,type:"file"},{kind:"symlink",target:I,rawTarget:L,stat:M})},Ze=async()=>{for(let[I,_]of[...g]){if(!H(n))return;if(_.kind==="file"){let D,ie;try{if(D=await Z.realpath(_.target),!H(n))return;ie=await Z.lstat(_.target)}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;ee(I,{path:I,size:null,type:"file",reason:ue(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(D!==_.realTarget||!ie.isFile()||ie.isSymbolicLink()||!Er(_.stat,ie)||ie.size!==_.stat.size||ie.mtimeMs!==_.stat.mtimeMs||ie.ctimeMs!==_.stat.ctimeMs)&&ee(I,{path:I,size:ie.isFile()?ie.size:null,type:ie.isFile()?"file":"other",reason:"changed-during-read"});continue}if(_.kind==="symlink"){let D,ie;try{if(D=await Z.lstat(_.target),!H(n))return;ie=await Z.readlink(_.target,{encoding:"buffer"})}catch(R){if(!H(n))return;if(!ue(R)&&!le(R))throw R;ee(I,{path:I,size:null,type:"other",reason:ue(R)?"unreadable":"changed-during-read"});continue}if(!H(n))return;(!D.isSymbolicLink()||!Er(_.stat,D)||D.mtimeMs!==_.stat.mtimeMs||D.ctimeMs!==_.stat.ctimeMs||!_.rawTarget.equals(ie))&&ee(I,{path:I,size:null,type:"other",reason:"changed-during-read"});continue}let T,L;try{if(T=await Z.realpath(_.target),!H(n))return;L=await Z.lstat(_.target)}catch{if(!H(n))return;ee(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;if(!(T===_.realTarget&&L.isDirectory()&&!L.isSymbolicLink()&&Er(_.stat,L)&&F(c,T)&&!dt(u,T))){ee(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"});continue}let M;try{if(!H(n))return;M=await Vv(n,T)}catch(D){if(Mi(D))throw D;ee(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!H(n))return;M.dirty?ee(I,{path:I,size:null,type:"directory",reason:"gitlink-dirty"}):M.hash!==_.hash&&ee(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"})}for(let[I,_]of b){if(!H(n))return;try{let T=await Z.lstat(_);if(!H(n))return;C({path:I,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!H(n))return;if(le(T))continue;if(!ue(T))throw T;C({path:I,size:null,type:"file",reason:"unreadable"})}}},$e=await Xv(n,e,a,t.gitSelectionHooks);if($e===null){let I=await Bv({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let L of I.records){if(L.type!=="file"&&L.type!=="symlink"||g.has(L.path))continue;if(ut(n)<1)break;if(!qv(i,L.path,n))continue;if(ut(n)<1)break;let Q=B.resolve(s,...L.path.split("/")),M;try{M=await Z.lstat(Q)}catch(D){if(!H(n))break;if(!ue(D)&&!le(D))throw D;C({path:L.path,size:null,type:"file",reason:le(D)?"changed-during-read":"unreadable"});continue}if(ut(n)<1)break;if(L.type==="symlink"&&M.isSymbolicLink()){if(await vt(Q,L.path,M),ut(n)<1)break;continue}if(L.type!=="file"||!M.isFile()||M.isSymbolicLink()){C({path:L.path,size:M.isFile()?M.size:null,type:M.isDirectory()?"directory":M.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await U(Q,L.path,M),ut(n)<1)break}ut(n)>=1&&await Ze();let _=await Bv({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o}),T=vR(I.evidence,_.evidence);N=T.evidence;for(let L of[...I.omissions,..._.omissions,...T.omissions])m.some(Q=>Q.path===L.path&&Q.reason===L.reason)||C(L)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let I=t.incrementalBaseline,_=new Map,T=!1;if(I){let R=Xr(I);for(let te of R.entries)te.gitObjectId!==void 0&&_.set(te.path,te);T=_.size>0}let L=new Set,Q=!0;try{let R=await ua(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(R.overflow)T=!1,Q=!1,_.clear();else for(let te of R.records){let ne=ys(te),Se=ne.indexOf(" "),Ne=Se<0?null:Wi(ne.slice(Se+1));if(Se!==1||Ne===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ne[0]!=="H"&&L.add(Ne)}}catch(R){if(Mi(R))throw R;T=!1,Q=!1,_.clear()}let M=new Set;try{let R=await ws(n,s,["ls-files","--modified","-z"],Qu);for(let te of R.toString("utf8").split("\0")){let ne=Wi(te);ne!==null&&M.add(ne)}}catch{T=!1,Q=!1,_.clear()}let D=new Set,ie=new Set;for(let R of eg($e)){if(g.has(R)||!la(e,R))continue;if(ut(n)<1)break;if(!qv(i,R,n))continue;if(ut(n)<1)break;let te=B.resolve(s,...R.split("/"));if(te===f||te===p||dt(d,te)||v.some(Oe=>dt(Oe,te)))continue;if($e.gitlinks.has(R)){if(h.length>=r.maxFiles){C({path:R,size:0,type:"file",reason:"file-count"});continue}let Oe,Wa;try{[Oe,Wa]=await Promise.all([Z.realpath(te),Z.lstat(te)])}catch{C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Wa.isSymbolicLink()||!Wa.isDirectory()||!F(c,Oe)||dt(u,Oe)){C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let di=await Vv(n,Oe);if(di.dirty){C({path:R,size:null,type:"directory",reason:"gitlink-dirty"});continue}await de({path:R,hash:di.hash,size:0,type:"file"},{kind:"gitlink",target:te,realTarget:Oe,stat:Wa,hash:di.hash})}catch(di){if(Mi(di))throw di;C({path:R,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ne;try{ne=await Z.lstat(te)}catch(Oe){if(le(Oe)&&$e.tracked.has(R)){b.set(R,te);continue}if(!ue(Oe)&&!le(Oe))throw Oe;C({path:R,size:null,type:"file",reason:le(Oe)?"changed-during-read":"unreadable"});continue}if(ne.isSymbolicLink()){await vt(te,R,ne);continue}if(!ne.isFile()){$e.nestedRepositories.has(R)||C({path:R,size:null,type:"other",reason:"changed-during-read"});continue}let Se=$e.trackedObjectIds.get(R),Ne=Se?_.get(R):void 0;if(T&&Ne?.gitObjectId!==void 0&&Ne.gitObjectId===Se&&!L.has(R)&&!M.has(R)){if(h.length>=r.maxFiles){C({path:R,size:Ne.size,type:"file",reason:"file-count"});continue}if(Ne.size>r.maxFileBytes){C({path:R,size:Ne.size,type:"file",reason:"file-size"});continue}if(k+Ne.size>r.maxTotalBytes){C({path:R,size:Ne.size,type:"file",reason:"total-size"});continue}h.push({...Ne}),k+=Ne.size,D.add(R);continue}let Zf=Q&&!L.has(R)&&!M.has(R)?Se:void 0;await U(te,R,ne,Zf),Zf!==void 0&&ie.add(R)}if(await Ze(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Qv(n,e,a,$e,t.gitSelectionHooks?.outputChunkBytes),D.size>0||T&&ie.size>0){let R=await ws(n,s,["ls-files","--modified","-z"],Qu),te=new Set;for(let ne of R.toString("utf8").split("\0")){let Se=Wi(ne);Se!==null&&te.add(Se)}for(let ne of D){if(!te.has(ne))continue;let Se=h.find(Ne=>Ne.path===ne);ee(ne,{path:ne,size:Se?.size??null,type:"file",reason:"changed-during-read"})}for(let ne of ie){if(!te.has(ne))continue;let Se=h.find(Ne=>Ne.path===ne);Se&&delete Se.gitObjectId}}for(let R of $e.omissions)C(R);$e.overflow&&O($e.overflow)}h.sort((I,_)=>I.path.localeCompare(_.path,"en")),m.sort((I,_)=>I.path.localeCompare(_.path,"en"));let cb=$e===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...$e.evidence?{gitSelection:$e.evidence}:{}},Qf=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:cb,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:m,omittedCount:S,...w>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:w}}:{}}),Ec=Qf();for(;id(Ec)>r.maxManifestBytes;){if(m.filter(_=>!Zu(_)).length>0){let _=Math.max(1,Math.ceil(m.length/4));for(let T=0;T<_;T+=1){let L=Ns(m);if(L===null)break;y(L)}}else if(h.length>0){let _=Math.max(1,Math.ceil(h.length/4));for(let T of h.splice(-_))S+=1,$(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ec=Qf()}return Ec}async function nd(e,t,r={}){let n=(await Ae(e.projectRoot))?.native.snapshot??Au;return ng(e,{...r,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Ss(e,t){let r=PR(e,t),i=me(e,r);await G(i,r);try{let n=await _v({root:i,file:r,maxBytes:LP,label:"Native baseline snapshot manifest"});return Xr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var gs,ed,LP,VP,FP,qP,MP,WP,zP,JP,GP,UP,KP,YP,XP,QP,ZP,eR,tR,ks,Jv,rR,zi,Qu,iR,nR,aR,td,oR,hR,Ji=A(()=>{"use strict";se();We();xt();bt();Y();ct();Gn();gs={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},ed=1e3,LP=8*1024*1024,VP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),qP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),MP=new Set(["schema","include","exclude","hash"]),WP=new Set(["provider","gitSelection","physicalSelection","projection"]),zP=new Set(["provider","selection"]),JP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),GP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),UP=new Set(["schema","status","before","after"]),KP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),YP=new Set(["path","hash","size","type","gitObjectId"]),XP=new Set(["path","size","type","reason"]),QP=new Set(["ref","hash","count"]),ZP=new Set(["change-created","legacy-migration","explicit"]),eR=new Set(["file","directory","other"]),tR=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"]),ks=/^[a-f0-9]{64}$/u,Jv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,rR=new Set(["EACCES","EPERM"]),zi=64*1024,Qu=64*1024,iR=6e4,nR=1e3,aR=2,td={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},oR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};hR=(1n<<256n)-1n});var Ue,Gi=A(()=>{"use strict";Ue=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"})});var Es=A(()=>{"use strict"});var ag=A(()=>{"use strict"});var ad=A(()=>{"use strict";Es()});var og=A(()=>{"use strict";Es();ad()});var jR,sg=A(()=>{"use strict";jR=fi(Jr(),1);_i();pr();Kr()});var UD,cg=A(()=>{"use strict";_i();Kr();UD=4*1024*1024});function OR(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function lg(e,t){return(...r)=>{let i=$R;if(i===null)return t(...r);let n=OR(`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 $R,ug=A(()=>{"use strict";$R=null});var ZD,dg=A(()=>{"use strict";ug();Ai();ZD=lg("hookWritePolicy",async e=>(await wu(e))?.hook??{allow_paths:[]})});var fg=A(()=>{"use strict";Es();_i();ag();og();pr();sg();Kr();Ai();ku();cg();dg();yu();ad()});var pg=A(()=>{"use strict";fg();Un()});import DR from"path";function pa(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function fa(e,t){let r=pa(e,t);if(DR.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function BR(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function mg(e){if(!e.run_id)return null;let t=pa(e,"run_id"),r=pa(e,"skill"),i=pa(e,"skill_version"),n=pa(e,"skill_hash"),a=fa(e,"pending_ref"),o=fa(e,"trajectory_ref"),s=fa(e,"context_ref"),c=fa(e,"artifacts_ref"),l=fa(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:hg(e,"current_step"),iteration:u,pending:hg(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:BR(e)}}var hg,XB,vg=A(()=>{"use strict";pg();hg=(e,t)=>{let r=e[t];return r==null?null:String(r)};XB=256*1024});function VR(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=mg(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function od(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!LR.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return VR(t)}var LR,gg=A(()=>{"use strict";vg();Gi();LR=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{constants as Cs,promises as ft}from"node:fs";import pt from"node:path";import{TextDecoder as FR}from"node:util";function Ps(e,t){let r=pt.relative(e,t);return r===""||!pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${pt.sep}`)}function qR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function xs(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function MR(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Rs(e,t,r){let i=Ue[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=pt.resolve(e),a=pt.resolve(n,...i.slice(8).split("/"));if(!Ps(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function wg(e){let t=await ft.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await ft.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function WR(e,t){let r=pt.resolve(e),i=pt.resolve(t);if(!Ps(r,i))throw new Error("Native Run path is outside its change");let n=[await wg(r)],a=r;for(let o of pt.relative(r,i).split(pt.sep).filter(Boolean)){a=pt.join(a,o);let s;try{s=await wg(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ps(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function yg(e){for(let t of e){let r=await ft.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!MR(t,r)||await ft.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function zR(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 As(e,t,r,i,n){let a=await WR(e,pt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await ft.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=qR(o),c=await ft.realpath(t);if(!Ps(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Cs.O_RDONLY:Cs.O_RDONLY|Cs.O_NOFOLLOW|Cs.O_NONBLOCK,u;try{u=await ft.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),ft.lstat(t),ft.realpath(t)]);if(await yg(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!xs(s,d)||!xs(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let v=await zR(u,r,i);await n?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([u.stat(),ft.lstat(t),ft.realpath(t)]);if(await yg(a),!m.isFile()||m.isSymbolicLink()||g!==c||!xs(s,h)||!xs(s,m))throw new Error(`${i} changed while reading`);let b;try{b=new FR("utf-8",{fatal:!0}).decode(v)}catch(S){throw new Error(`${i} is not valid UTF-8`,{cause:S})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}function Ng(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function sd(e){return od(e)}async function Ki(e,t){let r=Rs(e,"stateRef"),i=await As(e,r,Ui.runStateBytes,"Native Run state",t);return i?od(Ng(i.text,"Native Run state")):null}async function Qr(e,t,r){let i=Rs(e,"trajectoryRef",t),n=await As(e,i,Ui.trajectoryBytes,"Native Run trajectory",r);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ui.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ui.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function bg(e,t,r){return(await As(e,Rs(e,"trajectoryRef",t),Ui.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function _s(e,t,r){let i=await As(e,Rs(e,"checkpointRef",t),Ui.checkpointBytes,"Native Run checkpoint",r);return i?Ng(i.text,"Native Run checkpoint"):null}var Ui,Zr=A(()=>{"use strict";Gi();gg();se();bt();Ui={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});import{createHash as JR}from"crypto";import GR from"path";function cd(e){return JR("sha256").update(e).digest("hex")}function KR(e,t){if(!UR.test(t))throw new Error(`Invalid Native change name: ${t}`);return GR.join(K(e,t),"trajectory.jsonl")}function YR(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function XR(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function QR(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=YR(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
159
+ `)])}catch(d){if(!XR(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:cd(t),targetHash:cd(l),tailHash:cd(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function ZR(e,t){let r=KR(e,t);await G(me(e,r),r);let i=K(e,t),n=await bg(i,Ue.trajectoryRef);return n===null?{status:"clean",file:r}:QR(r,Buffer.from(n))}async function kg(e,t){let r=await ZR(e,t);return"inspection"in r?r.inspection:r}var UR,Is=A(()=>{"use strict";Gi();lt();Y();Zr();UR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as eA}from"node:crypto";import{promises as Ts}from"node:fs";import Ft from"node:path";function Yi(e){return rA.has(e)}function Pg(e,t){let r=Ft.relative(e,t);return Ft.isAbsolute(r)||r===".."||r.startsWith(`..${Ft.sep}`)?null:r.replaceAll("\\","/")||"."}function Rg(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Ag(e,t){if(e.length===0||Rg(e)||e.includes("\\")||Ft.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=Ft.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function dd(e,t){return eA("sha256").update(`${e}
160
+ ${t}`).digest("hex")}async function Eg(e,t){let r=await Ts.realpath(t),i=await Ts.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ud==="win32"?Ft.normalize(r).toLowerCase():r;return dd(e,`${n}
161
161
  ${i.dev}
162
162
  ${i.ino}
163
- ${i.birthtimeMs}`)}async function Cg(e,t){let r=await Ts.realpath(t),i=await Ts.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ud==="win32"?Vt.normalize(r).toLowerCase():r;return dd(e,n)}function iA(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 ld(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Rg(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function _g(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ld(e.changeBranch,"Native workspace change branch"),ld(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 nA(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"||!Sg.test(t.baseCommit)||typeof t.targetCommit!="string"||!Sg.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ld(t.targetBranch,"Native workspace Git target branch")}function js(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"||!ha.test(String(t.projectRootId))||!ha.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");iA(t.capturedAt),Ag(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&&!ha.test(String(t.projectRootPathId))||a&&!ha.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ha.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&nA(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(_g(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 aA(e,t){return Vt.join(K(e,t),"workspace.json")}function oA(e,t){let r=aA(e,t),i=me(e,r),n=Pg(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Ag(n,"Native workspace file ref")}}async function sA(e,t){try{let r=oA(e,t),i=await ae({root:r.root,ref:r.ref,maxBytes:tA});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ma(e,t){let r=Ee(e.projectRoot),i={projectRoot:Vt.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await Ft(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await va({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function cA(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Pg(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=Ee(e.paths.projectRoot),i=r.isGitWorktree?Lr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Lr(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([Eg("comet.native.workspace-project-root.v2",e.paths.projectRoot),Eg("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Cg("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Cg("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&&_g(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:dd("comet.native.workspace-session.v2",`${s}
163
+ ${i.birthtimeMs}`)}async function Cg(e,t){let r=await Ts.realpath(t),i=await Ts.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=ud==="win32"?Ft.normalize(r).toLowerCase():r;return dd(e,n)}function iA(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 ld(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Rg(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function _g(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ld(e.changeBranch,"Native workspace change branch"),ld(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 nA(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"||!Sg.test(t.baseCommit)||typeof t.targetCommit!="string"||!Sg.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ld(t.targetBranch,"Native workspace Git target branch")}function js(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"||!ha.test(String(t.projectRootId))||!ha.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");iA(t.capturedAt),Ag(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&&!ha.test(String(t.projectRootPathId))||a&&!ha.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ha.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&nA(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(_g(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 aA(e,t){return Ft.join(K(e,t),"workspace.json")}function oA(e,t){let r=aA(e,t),i=me(e,r),n=Pg(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Ag(n,"Native workspace file ref")}}async function sA(e,t){try{let r=oA(e,t),i=await ae({root:r.root,ref:r.ref,maxBytes:tA});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ma(e,t){let r=Ee(e.projectRoot),i={projectRoot:Ft.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await qt(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await va({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function cA(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Pg(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=Ee(e.paths.projectRoot),i=r.isGitWorktree?Lr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Lr(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([Eg("comet.native.workspace-project-root.v2",e.paths.projectRoot),Eg("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Cg("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Cg("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&&_g(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:dd("comet.native.workspace-session.v2",`${s}
164
164
  ${c}
165
- ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return js(p),p}async function Ft(e,t){let r=await sA(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(js(r),r)}async function $s(e){js(e.identity);let t=await cA({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")),ud==="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 va(e){if(js(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 $s(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=Ee(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 Ig(e,t){let r=await Ft(e,t);if(r===null)return null;let i=await va({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var ha,Sg,tA,ud,rA,xr=A(()=>{"use strict";vt();se();it();ct();Y();ha=/^[a-f0-9]{64}$/u,Sg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tA=16*1024,ud=process.platform,rA=new Set(["workspace-root-changed","workspace-inspection-unavailable"])});import{promises as jg}from"fs";import qt from"path";function ya(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dg(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 Bs(e){if(!Hg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function gA(e){if(!Hg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Bg(e,t){if(e.length===0||qt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function wA(e,t){let r=ya(e,`spec_changes[${t}]`);if(Dg(r,fA,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(gA(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"&&Bg(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"||!pd.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"||!pd.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 yA(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 md(e,t){if(Dg(e,t,Pr),typeof e.name!="string")throw new Error("Native change name is required");if(Bs(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"||!pA.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&&!hA.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(wA),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"||!mA.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"&&Bg(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!yA(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 Li(e){let t=ya(e,Pr);if(t.schema!==kr)throw new Error(`Expected ${kr}`);return{schema:kr,...md(t,uA)}}function wa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fd(e,t,r){if(e===null)return null;let i=typeof e=="string"?vA.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 NA(e){if(e==null)return null;if(typeof e!="string"||!pd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function bA(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 Vi(e){let t=ya(e,Pr);if(t.schema!==br)throw new Error(`Expected ${br}`);if(wa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${br} minimum_runtime_version must be 2`);return{schema:br,minimum_runtime_version:2,revision:wa(t.revision,"Native v2 revision"),...md(t,Og)}}function Sr(e){let t=ya(e,Pr);if(t.schema!==Nr){if(t.schema===kr||t.schema===br){let o=t.schema===kr?Li(t):Vi(t);throw new Os(o.name,o.schema)}throw new ei(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=wa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ei(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=wa(t.revision,"Native revision"),n=md(t,dA),a=NA(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Nr,minimum_runtime_version:3,revision:i,verification_protocol:bA(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:fd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:fd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:fd(t.partial_allowance,"Native partial_allowance","allowances")}}function Lg(e){let t=ya(e,Pr);if(t.schema===kr){let n=Li(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Nr}`}}if(t.schema===br){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Nr}`}}if(t.schema!==Nr){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 ei(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=wa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ei(t.schema,r).message};let i=Sr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function ye(e,t){Bs(t);let r=qt.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Ls(e,t){let r=K(e,t),i=qt.join(r,"schema-migration.json");await G(F(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Vg(e,t){let r=K(e,t),i=qt.join(r,"checkpoint-journal.json");await G(F(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Fg(e,t=qt.dirname(e)){let r=qt.relative(t,e).split(qt.sep).join("/"),i=await ae({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,hd.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 vd(e,t){let r=qt.join(ye(e,t),Pr);await G(e.nativeRoot,r);let i=Lg(await Fg(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Ls(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 kA(e,i.state),i)}async function qg(e,t){let r=qt.join(ye(e,t),Pr);await G(e.nativeRoot,r);let i=Lg(await Fg(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function kA(e,t){if(await Ss(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Mt(e,t){let r=await vd(e,t);if(r.status==="migration-required")throw new Os(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ei(r.schema,r.minimumRuntimeVersion);return await Ig(e,t),r.state}var hd,$g,uA,Og,dA,fA,pA,hA,mA,Pr,pd,Hg,vA,Os,ei,Hs,ga,Ds,KL,ge=A(()=>{"use strict";hd=fi(Jr(),1);vt();it();se();Gr();We();ct();Y();st();Ov();Ji();Is();xr();fs();$g=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],uA=new Set($g),Og=new Set([...$g,"minimum_runtime_version","revision"]),dA=new Set([...Og,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),fA=new Set(["capability","operation","source","base_hash"]),pA=new Set(["shape","build","verify","archive"]),hA=new Set(["implicit","confirmed"]),mA=new Set(["pending","pass","fail"]),Pr="comet-state.yaml",pd=/^[a-f0-9]{64}$/u,Hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vA=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Os=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ei=class extends Error{constructor(r,i){super(r!==Nr||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"},Hs=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"},ga=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"},Ds=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"},KL=Ko("en")});import{execFileSync as $A}from"node:child_process";function DA(e,t){try{return $A("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:OA,maxBuffer:HA,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new bd(e,t,i)}}function Wt(e,t){return DA(e,t).trim()}var OA,HA,bd,Qi=A(()=>{"use strict";OA=3e4,HA=8*1024*1024,bd=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});var kd=A(()=>{"use strict";Qi();se()});var bV,qs=A(()=>{"use strict";bV=["$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 Sd=A(()=>{"use strict"});function Ke(e){return e.replace(BA,"$1 [REDACTED]").replace(LA,"[REDACTED PRIVATE KEY]").replace(VA,"$1[REDACTED]@").replace(FA,"[REDACTED TOKEN]").replace(qA,'$1"[REDACTED]"').replace(MA,"$1$2$1$3$4[REDACTED]$4").replace(WA,"$1$2[REDACTED]")}var BA,LA,VA,FA,qA,MA,WA,ti=A(()=>{"use strict";BA=/\b(Bearer|Basic)\s+[^\s"']+/giu,LA=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,VA=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,FA=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,qA=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,MA=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,WA=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});var Ed=A(()=>{"use strict";qs();Sd();ti()});var ka=A(()=>{"use strict"});var Ms=A(()=>{"use strict";ka()});var nw=A(()=>{"use strict"});var HV,aw=A(()=>{"use strict";qs();HV=8*1024*1024});var ow=A(()=>{"use strict";aw()});var Ws,Cd=A(()=>{"use strict";Qi();vt();We();kd();ra();Y();Ws=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import Zi from"node:path";import{promises as sw}from"node:fs";function XA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function QA(e,t){return Zi.join(gr(e,t),"supervisor")}function zs(e,t){return Zi.join(QA(e,t),"state.json")}function cw(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==xd)throw new Error(`Native Supervisor state schema must be ${xd}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(ri(t.integration.targetCommit,"Native Supervisor target commit"),ri(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");ri(n.candidateCommit,"Native Supervisor integration candidate commit"),ri(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&ri(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(ri(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Rr(e,t,r={}){try{let i=await sw.readFile(zs(e,t),"utf8"),n=JSON.parse(i);if(cw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(Ea(),dw)),{readNativePortableState:l}=await Promise.resolve().then(()=>(yr(),Mu)),u=await l(Zi.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:Zi.join(o.changesDir,t),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:p})=>p===f.name)&&(f.acceptanceScope=uw(d.contract,f.name),f.contractHash=j("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(yr(),Mu)),s=await o(Zi.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pd(e,t){cw(t),await sw.mkdir(e.changesRuntimeDir,{recursive:!0}),await Me(zs(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function ri(e,t){if(!YA.test(e))throw new Error(`${t} must be a Git commit`)}function ZA(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function lw(e){ri(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:uw(e.contract,i.name),contractHash:j("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:xd,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function uw(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Rd(e){let t=XA(e.parent),r=Lr(e.paths.projectRoot,t);if(!r)return null;let i=Lr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=er(e.paths.projectRoot).map(o=>Zi.resolve(o)).find(o=>Ee(o).currentBranch===t);if(!n)return null;let a=lw({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ZA(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Ad(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var xd,YA,Sa=A(()=>{"use strict";kd();se();pe();Ed();Ms();ct();Y();We();vt();nw();Qi();ow();Cd();xd="comet.native.supervisor.v2",YA=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var dw={};ep(dw,{NATIVE_CHILDREN_FILE:()=>_d,NATIVE_CHILDREN_SCHEMA:()=>ii,NATIVE_CHILDREN_SCHEMA_V2:()=>$d,NATIVE_CHILDREN_V2_SCHEMA:()=>ni,findNativeV1SupervisorParents:()=>kw,hasNativeSupervisorShapeIntent:()=>Nw,hashNativeParentContract:()=>Dd,inspectNativeChildren:()=>Ca,nativeChildrenAcceptanceValidation:()=>Od,nativeChildrenIndexDrift:()=>ww,parseNativeChildrenContract:()=>yw,readNativeChildrenContract:()=>en,readNativeSupervisorShapeIntent:()=>Hd});import{promises as Td}from"node:fs";import Ie from"node:path";function Gs(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Js(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function pw(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Id(e,t){let r=Ie.normalize(Ie.resolve(e)),i=Ie.normalize(Ie.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function a_(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function hw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function ww(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===$d&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!mw(e.children,l)),vw(i)?i:null}if(e.schema===ii&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!mw(e.children,a)),vw(i)?i:null}return null}function mw(e,t){return e.some(r=>r.covers.includes(t))}function vw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Od(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function o_(e){let t=Gs(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Gs(n,`Native children acceptance_index.${i}`);if(Js(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function s_(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function yw(e,t,r={}){let i=(0,jd.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Gs(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==ii&&a!==ni)throw Js(n,fw,"Native children contract"),new Error(`Native children schema must be ${ii} or ${ni}`);let o=a===ii?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Js(n,o==="indexed-v2"?t_:fw,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=Gs(f,`Native child ${p}`);if(Js(v,o==="indexed-v2"?n_:o==="summary-v2"?i_:r_,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!e_.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:pw(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?pw(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}a_(c);let d=r.policy==="advisory";if(a===$d){if(o==="indexed-v2"){let f=o_(n.acceptance_index);d||s_(f,t,r);let p=Object.keys(f);return d||hw(c,p,p),{schema:ni,acceptance_index:f,children:c}}return{schema:ni,children:c}}return t&&!d&&hw(c,t),{schema:ii,children:c}}async function en(e){let t=Ie.join(e.changeDir,_d);try{await Td.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ae({root:e.changeDir,ref:_d}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=yw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?ww(a,e.acceptanceIds,e.validation??{}):null}}function c_(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function Nw(e){let t=c_(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function Hd(e){try{let t=await ae({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return Nw(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Dd(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function bw(e){let t=er(e.projectRoot);t.some(i=>Id(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Ie.resolve(n)))]){let n=await Ae(i);n&&r.push({projectRoot:i,paths:await Ot(i,n.native.artifact_root),parent:Id(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function kw(e){let t=await bw(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Td.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=Ie.join(a.paths.changesDir,s.name),l;try{l=await Dt(Ie.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await en({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==ii||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:p})=>p.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:p,state:v})=>Ee(p.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let p=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(p)i.push(`Native Supervisor parent ${a} targets ${p.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await Ca({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let p=f.children.filter(({status:v})=>v!=="done").map(({name:v,status:h,message:m})=>`${v}=${h}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${p||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function l_(e,t){let r=Ie.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Dt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function u_(e,t){let r;try{r=await Td.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ie.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Dt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function d_(e,t,r){let i=Ie.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Ie.sep}`))return null;let n=i.split(Ie.sep).join("/");try{let a=(0,jd.parseDocument)(Wt(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:_e(a.toJS({mapAsMap:!1}))}catch{return null}}function f_(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function gw(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ca(e){let t=Ie.join(e.paths.changesDir,e.state.name),r=await Hd(t),i=null,n;try{n=await en({changeDir:t,validation:Od(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Rr(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Ad(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Dd({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===ni){let g=await Rr(e.paths,e.state.name,{diagnostics:!0});if(!g){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let E=await Rd({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});E&&(g=E,await Pd(e.paths,E))}}if(g){let w=Ad(g);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let b=new Map(n.contract.children.map(w=>[w.name,w])),S=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(E=>n.contract.children.filter(({name:k})=>k!==w.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of S){if(w.status!=="ready")continue;b.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:S,readyChildren:S.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let c=await bw(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let S of await u_(g,l)){let w={...S,source:g,committedState:d_(g,S.file,b)};u.set(S.state.name,[...u.get(S.state.name)??[],w])}for(let S of l){let w=await l_(g,S);w&&d.set(S,[...d.get(S)??[],{source:g,state:w}])}}let f=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===g.name&&gw(k,o));if(b){f.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let S=u.get(g.name)?.[0];if(S){f.set(g.name,{kind:"blocked",phase:S.state.phase,projectRoot:S.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(g.name)??[];w.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):w[0]&&f.set(g.name,f_(w[0].state,w[0].source,o))}let p=new Map(n.contract.children.map(g=>[g.name,g])),v=new Map,h=g=>{let b=v.get(g);if(b)return b;let S=p.get(g),E=S.depends_on.map(h).every(({status:O})=>O==="done"),k=f.get(g),x=k?.kind==="active"&&E?S.depends_on.filter(O=>!(u.get(O)??[]).some(({source:$,committedState:de})=>Id($.projectRoot,k.projectRoot)&&de?.name===O&&gw(de,o))):[],N,y=k?.message??null;k?.kind==="done"?(N=E?"done":"blocked",E||(y=`Native child ${g} was merged before its dependencies`)):k?.kind==="active"?(N=E&&x.length===0?"active":"blocked",E?x.length>0&&(y=`Native child ${g} does not include merged dependencies: ${x.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):k?.kind==="blocked"?N="blocked":(N=s&&E?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:S.summary,dependsOn:[...S.depends_on],covers:[...S.covers],status:N,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:y};return v.set(g,C),C},m=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:m.every(({status:g})=>g==="done")}}var jd,_d,ii,ni,$d,e_,fw,t_,r_,i_,n_,Ea=A(()=>{"use strict";jd=fi(Jr(),1);vt();Qi();it();pe();We();Y();yr();Sa();_d="children.yaml",ii="comet.native.children.v1",ni="comet.native.children.v2",$d=ni,e_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fw=new Set(["schema","children"]),t_=new Set(["schema","acceptance_index","children"]),r_=new Set(["name","depends_on","covers"]),i_=new Set(["name","summary","depends_on"]),n_=new Set(["name","depends_on","covers"])});import{createHash as jw}from"node:crypto";import xw from"path";function be(e,t){return e<t?-1:e>t?1:0}function Fd(e){if(!Wd.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function x_(e,t){return e===t?0:e===null?-1:t===null?1:be(e,t)}function _r(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=xw.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||xw.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function Hw(e,t){return e==="."?e:_r(e,t)}function tn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function P_(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:_r(e.path,`${t} path`),hash:e.hash,size:tn(e.size,`${t} size`),type:"file"}}function R_(e,t){return{path:Hw(e.path,`${t} path`),size:e.size===null?null:tn(e.size,`${t} size`),type:e.type,reason:e.reason}}function A_(e,t){return be(e.path,t.path)||be(e.hash,t.hash)||e.size-t.size}function __(e,t){return be(e.path,t.path)||be(e.reason,t.reason)||be(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ra(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
165
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return js(p),p}async function qt(e,t){let r=await sA(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(js(r),r)}async function $s(e){js(e.identity);let t=await cA({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")),ud==="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 va(e){if(js(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 $s(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=Ee(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 Ig(e,t){let r=await qt(e,t);if(r===null)return null;let i=await va({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var ha,Sg,tA,ud,rA,xr=A(()=>{"use strict";gt();se();nt();lt();Y();ha=/^[a-f0-9]{64}$/u,Sg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tA=16*1024,ud=process.platform,rA=new Set(["workspace-root-changed","workspace-inspection-unavailable"])});import{promises as jg}from"fs";import Mt from"path";function ya(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dg(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 Bs(e){if(!Hg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function gA(e){if(!Hg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Bg(e,t){if(e.length===0||Mt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function wA(e,t){let r=ya(e,`spec_changes[${t}]`);if(Dg(r,fA,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(gA(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"&&Bg(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"||!pd.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"||!pd.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 yA(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 md(e,t){if(Dg(e,t,Pr),typeof e.name!="string")throw new Error("Native change name is required");if(Bs(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"||!pA.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&&!hA.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(wA),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"||!mA.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"&&Bg(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!yA(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 Li(e){let t=ya(e,Pr);if(t.schema!==kr)throw new Error(`Expected ${kr}`);return{schema:kr,...md(t,uA)}}function wa(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fd(e,t,r){if(e===null)return null;let i=typeof e=="string"?vA.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 NA(e){if(e==null)return null;if(typeof e!="string"||!pd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function bA(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 Vi(e){let t=ya(e,Pr);if(t.schema!==br)throw new Error(`Expected ${br}`);if(wa(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${br} minimum_runtime_version must be 2`);return{schema:br,minimum_runtime_version:2,revision:wa(t.revision,"Native v2 revision"),...md(t,Og)}}function Sr(e){let t=ya(e,Pr);if(t.schema!==Nr){if(t.schema===kr||t.schema===br){let o=t.schema===kr?Li(t):Vi(t);throw new Os(o.name,o.schema)}throw new ei(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=wa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ei(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=wa(t.revision,"Native revision"),n=md(t,dA),a=NA(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Nr,minimum_runtime_version:3,revision:i,verification_protocol:bA(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:fd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:fd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:fd(t.partial_allowance,"Native partial_allowance","allowances")}}function Lg(e){let t=ya(e,Pr);if(t.schema===kr){let n=Li(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Nr}`}}if(t.schema===br){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Nr}`}}if(t.schema!==Nr){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 ei(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=wa(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ei(t.schema,r).message};let i=Sr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function ye(e,t){Bs(t);let r=Mt.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Ls(e,t){let r=K(e,t),i=Mt.join(r,"schema-migration.json");await G(F(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Vg(e,t){let r=K(e,t),i=Mt.join(r,"checkpoint-journal.json");await G(F(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Fg(e,t=Mt.dirname(e)){let r=Mt.relative(t,e).split(Mt.sep).join("/"),i=await ae({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,hd.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 vd(e,t){let r=Mt.join(ye(e,t),Pr);await G(e.nativeRoot,r);let i=Lg(await Fg(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Ls(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 kA(e,i.state),i)}async function qg(e,t){let r=Mt.join(ye(e,t),Pr);await G(e.nativeRoot,r);let i=Lg(await Fg(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function kA(e,t){if(await Ss(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Wt(e,t){let r=await vd(e,t);if(r.status==="migration-required")throw new Os(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ei(r.schema,r.minimumRuntimeVersion);return await Ig(e,t),r.state}var hd,$g,uA,Og,dA,fA,pA,hA,mA,Pr,pd,Hg,vA,Os,ei,Hs,ga,Ds,KL,ge=A(()=>{"use strict";hd=fi(Jr(),1);gt();nt();se();Gr();We();lt();Y();ct();Ov();Ji();Is();xr();fs();$g=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],uA=new Set($g),Og=new Set([...$g,"minimum_runtime_version","revision"]),dA=new Set([...Og,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),fA=new Set(["capability","operation","source","base_hash"]),pA=new Set(["shape","build","verify","archive"]),hA=new Set(["implicit","confirmed"]),mA=new Set(["pending","pass","fail"]),Pr="comet-state.yaml",pd=/^[a-f0-9]{64}$/u,Hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vA=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Os=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ei=class extends Error{constructor(r,i){super(r!==Nr||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"},Hs=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"},ga=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"},Ds=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"},KL=Ko("en")});import{execFileSync as $A}from"node:child_process";function DA(e,t){try{return $A("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:OA,maxBuffer:HA,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new bd(e,t,i)}}function zt(e,t){return DA(e,t).trim()}var OA,HA,bd,Qi=A(()=>{"use strict";OA=3e4,HA=8*1024*1024,bd=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});var kd=A(()=>{"use strict";Qi();se()});var bV,qs=A(()=>{"use strict";bV=["$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 Sd=A(()=>{"use strict"});function Ke(e){return e.replace(BA,"$1 [REDACTED]").replace(LA,"[REDACTED PRIVATE KEY]").replace(VA,"$1[REDACTED]@").replace(FA,"[REDACTED TOKEN]").replace(qA,'$1"[REDACTED]"').replace(MA,"$1$2$1$3$4[REDACTED]$4").replace(WA,"$1$2[REDACTED]")}var BA,LA,VA,FA,qA,MA,WA,ti=A(()=>{"use strict";BA=/\b(Bearer|Basic)\s+[^\s"']+/giu,LA=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,VA=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,FA=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,qA=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,MA=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,WA=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});var Ed=A(()=>{"use strict";qs();Sd();ti()});var ka=A(()=>{"use strict"});var Ms=A(()=>{"use strict";ka()});var nw=A(()=>{"use strict"});var HV,aw=A(()=>{"use strict";qs();HV=8*1024*1024});var ow=A(()=>{"use strict";aw()});var Ws,Cd=A(()=>{"use strict";Qi();gt();We();kd();ra();Y();Ws=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import Zi from"node:path";import{promises as sw}from"node:fs";function XA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function QA(e,t){return Zi.join(gr(e,t),"supervisor")}function zs(e,t){return Zi.join(QA(e,t),"state.json")}function cw(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==xd)throw new Error(`Native Supervisor state schema must be ${xd}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(ri(t.integration.targetCommit,"Native Supervisor target commit"),ri(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");ri(n.candidateCommit,"Native Supervisor integration candidate commit"),ri(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&ri(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(ri(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Rr(e,t,r={}){try{let i=await sw.readFile(zs(e,t),"utf8"),n=JSON.parse(i);if(cw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(Ea(),dw)),{readNativePortableState:l}=await Promise.resolve().then(()=>(yr(),Mu)),u=await l(Zi.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:Zi.join(o.changesDir,t),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:p})=>p===f.name)&&(f.acceptanceScope=uw(d.contract,f.name),f.contractHash=j("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(yr(),Mu)),s=await o(Zi.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Pd(e,t){cw(t),await sw.mkdir(e.changesRuntimeDir,{recursive:!0}),await Me(zs(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function ri(e,t){if(!YA.test(e))throw new Error(`${t} must be a Git commit`)}function ZA(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function lw(e){ri(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:uw(e.contract,i.name),contractHash:j("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:xd,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function uw(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Rd(e){let t=XA(e.parent),r=Lr(e.paths.projectRoot,t);if(!r)return null;let i=Lr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=er(e.paths.projectRoot).map(o=>Zi.resolve(o)).find(o=>Ee(o).currentBranch===t);if(!n)return null;let a=lw({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ZA(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Ad(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var xd,YA,Sa=A(()=>{"use strict";kd();se();pe();Ed();Ms();lt();Y();We();gt();nw();Qi();ow();Cd();xd="comet.native.supervisor.v2",YA=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var dw={};ep(dw,{NATIVE_CHILDREN_FILE:()=>_d,NATIVE_CHILDREN_SCHEMA:()=>ii,NATIVE_CHILDREN_SCHEMA_V2:()=>$d,NATIVE_CHILDREN_V2_SCHEMA:()=>ni,findNativeV1SupervisorParents:()=>kw,hasNativeSupervisorShapeIntent:()=>Nw,hashNativeParentContract:()=>Dd,inspectNativeChildren:()=>Ca,nativeChildrenAcceptanceValidation:()=>Od,nativeChildrenIndexDrift:()=>ww,parseNativeChildrenContract:()=>yw,readNativeChildrenContract:()=>en,readNativeSupervisorShapeIntent:()=>Hd});import{promises as Td}from"node:fs";import Ie from"node:path";function Gs(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Js(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function pw(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Id(e,t){let r=Ie.normalize(Ie.resolve(e)),i=Ie.normalize(Ie.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function a_(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function hw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function ww(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===$d&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!mw(e.children,l)),vw(i)?i:null}if(e.schema===ii&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!mw(e.children,a)),vw(i)?i:null}return null}function mw(e,t){return e.some(r=>r.covers.includes(t))}function vw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Od(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function o_(e){let t=Gs(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Gs(n,`Native children acceptance_index.${i}`);if(Js(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function s_(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function yw(e,t,r={}){let i=(0,jd.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Gs(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==ii&&a!==ni)throw Js(n,fw,"Native children contract"),new Error(`Native children schema must be ${ii} or ${ni}`);let o=a===ii?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Js(n,o==="indexed-v2"?t_:fw,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=Gs(f,`Native child ${p}`);if(Js(v,o==="indexed-v2"?n_:o==="summary-v2"?i_:r_,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!e_.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:pw(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?pw(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}a_(c);let d=r.policy==="advisory";if(a===$d){if(o==="indexed-v2"){let f=o_(n.acceptance_index);d||s_(f,t,r);let p=Object.keys(f);return d||hw(c,p,p),{schema:ni,acceptance_index:f,children:c}}return{schema:ni,children:c}}return t&&!d&&hw(c,t),{schema:ii,children:c}}async function en(e){let t=Ie.join(e.changeDir,_d);try{await Td.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await ae({root:e.changeDir,ref:_d}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=yw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?ww(a,e.acceptanceIds,e.validation??{}):null}}function c_(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function Nw(e){let t=c_(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function Hd(e){try{let t=await ae({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return Nw(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Dd(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function bw(e){let t=er(e.projectRoot);t.some(i=>Id(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Ie.resolve(n)))]){let n=await Ae(i);n&&r.push({projectRoot:i,paths:await Ht(i,n.native.artifact_root),parent:Id(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function kw(e){let t=await bw(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Td.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=Ie.join(a.paths.changesDir,s.name),l;try{l=await Bt(Ie.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await en({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==ii||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:p})=>p.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:p,state:v})=>Ee(p.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let p=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(p)i.push(`Native Supervisor parent ${a} targets ${p.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await Ca({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let p=f.children.filter(({status:v})=>v!=="done").map(({name:v,status:h,message:m})=>`${v}=${h}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${p||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function l_(e,t){let r=Ie.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Bt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function u_(e,t){let r;try{r=await Td.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ie.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Bt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function d_(e,t,r){let i=Ie.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Ie.sep}`))return null;let n=i.split(Ie.sep).join("/");try{let a=(0,jd.parseDocument)(zt(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:_e(a.toJS({mapAsMap:!1}))}catch{return null}}function f_(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function gw(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ca(e){let t=Ie.join(e.paths.changesDir,e.state.name),r=await Hd(t),i=null,n;try{n=await en({changeDir:t,validation:Od(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Rr(e.paths,e.state.name,{diagnostics:!0});if(g){let b=Ad(g);return{...b,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Dd({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===ni){let g=await Rr(e.paths,e.state.name,{diagnostics:!0});if(!g){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let E=await Rd({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});E&&(g=E,await Pd(e.paths,E))}}if(g){let w=Ad(g);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let b=new Map(n.contract.children.map(w=>[w.name,w])),S=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(E=>n.contract.children.filter(({name:k})=>k!==w.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of S){if(w.status!=="ready")continue;b.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:S,readyChildren:S.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let c=await bw(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let b=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let S of await u_(g,l)){let w={...S,source:g,committedState:d_(g,S.file,b)};u.set(S.state.name,[...u.get(S.state.name)??[],w])}for(let S of l){let w=await l_(g,S);w&&d.set(S,[...d.get(S)??[],{source:g,state:w}])}}let f=new Map;for(let g of n.contract.children){let b=(u.get(g.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===g.name&&gw(k,o));if(b){f.set(g.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let S=u.get(g.name)?.[0];if(S){f.set(g.name,{kind:"blocked",phase:S.state.phase,projectRoot:S.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(g.name)??[];w.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):w[0]&&f.set(g.name,f_(w[0].state,w[0].source,o))}let p=new Map(n.contract.children.map(g=>[g.name,g])),v=new Map,h=g=>{let b=v.get(g);if(b)return b;let S=p.get(g),E=S.depends_on.map(h).every(({status:O})=>O==="done"),k=f.get(g),x=k?.kind==="active"&&E?S.depends_on.filter(O=>!(u.get(O)??[]).some(({source:$,committedState:de})=>Id($.projectRoot,k.projectRoot)&&de?.name===O&&gw(de,o))):[],N,y=k?.message??null;k?.kind==="done"?(N=E?"done":"blocked",E||(y=`Native child ${g} was merged before its dependencies`)):k?.kind==="active"?(N=E&&x.length===0?"active":"blocked",E?x.length>0&&(y=`Native child ${g} does not include merged dependencies: ${x.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):k?.kind==="blocked"?N="blocked":(N=s&&E?"ready":"pending",s||(y="Parent Shape confirmation is required"));let C={name:g,summary:S.summary,dependsOn:[...S.depends_on],covers:[...S.covers],status:N,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:y};return v.set(g,C),C},m=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:m.every(({status:g})=>g==="done")}}var jd,_d,ii,ni,$d,e_,fw,t_,r_,i_,n_,Ea=A(()=>{"use strict";jd=fi(Jr(),1);gt();Qi();nt();pe();We();Y();yr();Sa();_d="children.yaml",ii="comet.native.children.v1",ni="comet.native.children.v2",$d=ni,e_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fw=new Set(["schema","children"]),t_=new Set(["schema","acceptance_index","children"]),r_=new Set(["name","depends_on","covers"]),i_=new Set(["name","summary","depends_on"]),n_=new Set(["name","depends_on","covers"])});import{createHash as jw}from"node:crypto";import xw from"path";function be(e,t){return e<t?-1:e>t?1:0}function Fd(e){if(!Wd.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function x_(e,t){return e===t?0:e===null?-1:t===null?1:be(e,t)}function _r(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=xw.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||xw.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function Hw(e,t){return e==="."?e:_r(e,t)}function tn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function P_(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:_r(e.path,`${t} path`),hash:e.hash,size:tn(e.size,`${t} size`),type:"file"}}function R_(e,t){return{path:Hw(e.path,`${t} path`),size:e.size===null?null:tn(e.size,`${t} size`),type:e.type,reason:e.reason}}function A_(e,t){return be(e.path,t.path)||be(e.hash,t.hash)||e.size-t.size}function __(e,t){return be(e.path,t.path)||be(e.reason,t.reason)||be(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ra(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
166
166
  `,"utf8")}function Ar(e,t,r){let i=`${t}
167
167
  ${vn(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function I_(e){if(Ra(e)<=oi)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=jw("sha256");a.update(`${S_}
168
- `),e.omissionOverflow&&Ar(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(i+=1),n+=1,Ar(a,"omission",f)},s=f=>{i+=1,n+=1,Ar(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let p=r[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(f,1),p}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Ra(u)>oi;){if(r.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(r.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function qd(e){let t=Xr(e),r=t.entries.map((n,a)=>P_(n,`Snapshot entry ${a}`));if(r.sort(A_),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>R_(n,`Snapshot omission ${a}`));return i.sort(__),I_({schema:$w,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Aa(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:_r(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>be(r.path,i.path)||be(r.kind,i.kind))}function _a(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Pw(e){return e?{hash:e.hash,size:e.size}:null}function zd(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:be(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:Pw(c),after:Pw(l)})}}function Dw(e,t){return{...e,attributedTo:t.filter(r=>_a(r,e.path))}}function Jd(e){let t=Aa(e.declaredArtifacts),r=[];return zd(e.baseline,e.current,i=>{r.push(Dw(i,t))}),r}function zt(e,t){return{id:`scope:${j(b_,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function T_(e,t){let r=t.omitted.map(i=>zt({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(zt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(zt({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function Rw(e,t){return T_(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Md(e,t){return be(e.kind,t.kind)||be(e.source,t.source)||x_(e.path,t.path)||be(e.id,t.id)}function j_(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Md)}function Bw(e){return[...new Set(e.map((t,r)=>_r(t,`Git path ${r}`)))].sort(be)}function Aw(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function $_(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Lw(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Bw(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Aw(e.baseCommit,"Native external drift base commit"),targetBranch:$_(e.targetBranch,"Native external drift target branch"),targetCommit:Aw(e.targetCommit,"Native external drift target commit"),paths:t}}function Vw(e){if(typeof e.contractHash!="string"||!Wd.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Aa(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Bw(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Lw(e.externalDrift)}}}function O_(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,f=0;return zd(e,t,p=>{let v=r.some(h=>_a(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<E_){let h=Dw(p,r),m=Ra(h);l+m<=oi?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Fw(e,t){return zt({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function H_(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:tn(Number(t[1]),"Scope overflow change count"),unresolved:tn(Number(t[2]),"Scope overflow unresolved count"),unattributed:tn(Number(t[3]),"Scope overflow unattributed count")},i=ai(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Fw(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function D_(e){let t=jw("sha256");t.update(`${k_}
169
- `);let r=0;zd(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Ar(t,"change",n);let a=0;for(let o of e.declaredArtifacts)_a(o,n.path)&&(a+=1,Ar(t,"change-attribution",o));Ar(t,"change-end",{attributionCount:a}),a===0&&Ar(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Ar(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function qw(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=O_(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),N=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!N.has(C)||n.some(O=>_a(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(xa,e),c=j(xa,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,N]of[["baseline",e],["current",t]])for(let y of N.omitted){if(l.length>=C_)break;l.push(zt({kind:"snapshot-omission",source:x,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${x} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Rw("baseline",e),...Rw("current",t),...o.totalChanges===0&&a===null?[zt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(N=>x.has(N)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(N=>!x.has(N))}},v=x=>{let N=o.candidates.slice(0,x.detailedChangeCount),y=N.filter(Qe=>Qe.attributedTo.length===0&&!u.has(Qe.path)),C=o.totalChanges-N.length,O=o.totalUnattributed-y.length,$=d-x.detailedOmissionCount,de=O+$,ee=[...y.map(Qe=>zt({kind:"unattributed-change",source:"implementation-scope",path:Qe.path,evidence:{after:Qe.after,before:Qe.before,changeKind:Qe.kind}},`Changed path is not covered by a declared artifact: ${Qe.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...de>0?[Fw(x.overflowHash,{changes:C,unattributed:O,unresolved:de})]:[]],U=j_(ee),mt=x.includeGitAdvisory?p():void 0;return{schema:Vd,contractHash:i,baselineProjectionRef:Fd(s),baselineProjectionHash:s,currentProjectionRef:Fd(c),currentProjectionHash:c,complete:U.length===0,declaredArtifacts:n,changes:N,unattributed:y,unresolvedScopes:U,noCodeReason:a,...mt?{gitAdvisory:mt}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,m=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:b});if(Ra({...x,scopeHash:b})<=oi)break;if(g){g=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let w=o.totalChanges>h||d>m?D_({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):b,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:w}),k={...E,scopeHash:j(Ow,E)};if(Ra(k)>oi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return k}function Gd(e){let t=qd(e.baseline),r=qd(e.current),i=Vw(e);return{authority:i,baseline:t,current:r,scope:qw(t,r,i)}}function Rt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function At(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function ai(e,t){if(typeof e!="string"||!Wd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _w(e,t,r){let i=Fd(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function Qs(e,t){let r=Rt(e,"Native snapshot projection");if(At(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==$w)throw new Error("Native snapshot projection schema is invalid");let i=Xr({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=qd(i);if(j(xa,r)!==j(xa,n))throw new Error("Native snapshot projection is not canonical");let a=j(xa,n);if(t!==void 0&&ai(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ud(e,t){let r=Rt(e,`Declared artifact ${t}`);if(At(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:_r(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Iw(e,t){if(e===null)return null;let r=Rt(e,t);return At(r,["hash","size"],[],t),{hash:ai(r.hash,`${t} hash`),size:tn(r.size,`${t} size`)}}function Tw(e,t){let r=Rt(e,`Implementation change ${t}`);if(At(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Ud),n=Aa(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Iw(r.before,`Implementation change ${t} before`),o=Iw(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:_r(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function L_(e,t){let r=Rt(e,`Unresolved scope ${t}`);At(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?Hw(r.path,`Unresolved scope ${t} path`):_r(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Pa(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>_r(n,`${t} ${a}`)),i=[...new Set(r)].sort(be);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function Mw(e){let t=Rt(e,"Native implementation external drift");if(At(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Pa(t.paths,"Native external drift paths");return Lw({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Zs(e){let t=Rt(e,"Native implementation scope"),r=[...B_].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(At(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Vd)throw new Error("Native implementation scope schema is invalid");let i=ai(t.contractHash,"Implementation scope contractHash"),n=ai(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_w(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ai(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_w(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Ud);if(JSON.stringify(c)!==JSON.stringify(Aa(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Tw),u=[...l].sort((y,C)=>be(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>_a(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Tw),p=t.externalDrift===void 0?void 0:Mw(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!v.has(y.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(L_),g=m.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:H_(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,w=[...h.map(y=>zt({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&S===null?[zt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Md))||new Set(m.map(y=>y.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(w.sort(Md))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let k;if(t.gitAdvisory!==void 0){let y=Rt(t.gitAdvisory,"Implementation scope Git advisory");if(At(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Pa(y.changedPaths,"Git changed paths"),O=Pa(y.pathsPresentInSnapshotChanges,"Git present paths"),$=Pa(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),de=[...O,...$].sort(be);if(JSON.stringify(de)!==JSON.stringify(C)||$.some(ee=>l.some(U=>U.path===ee)))throw new Error("Implementation scope Git advisory partition is invalid");k={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:$}}let x={schema:Vd,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...k?{gitAdvisory:k}:{},...p?{externalDrift:p}:{}},N=ai(t.scopeHash,"Implementation scope scopeHash");if(j(Ow,x)!==N)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:N}}function V_(e){let t=Rt(e,"Native implementation scope authority");if(At(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Ud);if(JSON.stringify(r)!==JSON.stringify(Aa(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=Pa(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Mw(t.externalDrift),a=Vw({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Ia(e){let t=Rt(e,"Native implementation scope bundle");At(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=V_(t.authority),i=Qs(t.baseline),n=Qs(t.current),a=Zs(t.scope),o=qw(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function Ww(e){let t=Zs(e.scope);return Ia({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var Vd,$w,xa,Ow,b_,k_,S_,Wd,oi,E_,C_,B_,si=A(()=>{"use strict";pe();Ji();Vd="comet.native.implementation-scope.v2",$w="comet.native.content-snapshot-projection.v1",xa="comet.native.content-snapshot-projection.v1",Ow="comet.native.implementation-scope.v2",b_="comet.native.unresolved-scope-id.v1",k_="comet.native.scope-detail-overflow.v1",S_="comet.native.snapshot-projection-overflow.v2",Wd=/^[a-f0-9]{64}$/u,oi=1024*1024,E_=128,C_=128;B_=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import zw from"node:path";function Jt(e,t){if(!Gw.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Uw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Kw(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Kd(e,t,r=2e3){let i=Ke(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Ta(e,t){let r=zw.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||zw.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function W_(e,t,r){let i=Ta(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=yt(i),a=i.toLowerCase(),o=r?Ta(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Yd(e){let t=Ta(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function rn(e,t){return e<t?-1:e>t?1:0}function ec(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tc(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Yw(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Jw(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function z_(e){let t=ec(e,"Native acceptance trace");if(tc(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Gw.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=Ta(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=ec(o,`Native acceptance trace entry ${s}`);if(tc(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Yd(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(rn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Ta(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Kd(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>rn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=Jt(t.traceHash,"Native acceptance trace hash");if(j(F_,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Xw(e){let t=ec(e,"Native partial allowance");if(tc(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(rn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:Kw(t.change),scopeHash:Jt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Kd(t.reason,"Partial allowance reason"),confirmedSummary:Kd(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Uw(t.sourceRevision),confirmedAt:Yw(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=Jt(t.allowanceHash,"Native partial allowance hash");if(j(q_,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Xd(e){let t=ec(e,"Native verification evidence");if(tc(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=Jt(t.implementationScopeHash,"Native verification implementation scope hash"),i=z_(t.acceptanceTrace),n=Jt(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Jt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Yd(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(rn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(rn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Yd(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(rn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Kw(t.change),sourceRevision:Uw(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Jt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Jw(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:W_(t.reportRef,"Native verification report ref"),reportHash:Jt(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:Jw(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Yw(t.createdAt,"Native verification timestamp")},d=Jt(t.envelopeHash,"Native verification envelope hash");if(j(M_,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var Gw,F_,q_,M_,rc=A(()=>{"use strict";pe();ti();Gn();si();Gw=/^[a-f0-9]{64}$/u,F_="comet.native.acceptance-trace.v2",q_="comet.native.partial-allowance.v1",M_="comet.native.verification-evidence.v2"});import Qw from"node:path";function Ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tr(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Gt(e,t){if(typeof e!="string"||!G_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Be(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ny(e,t){let r=Be(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function ry(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function eI(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>X_||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=Qw.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Qw.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function tI(e){let t=Ir(e,"Native check receipt checker");Tr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Ir(t.limits,"Native check receipt limits");if(Tr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==nn||t.version!==Qd||t.hash!==ey||r.maxFiles!==Te.maxFiles||r.maxFileBytes!==Te.maxFileBytes||r.maxTotalBytes!==Te.maxTotalBytes||r.maxIssues!==Te.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:nn,version:Qd,hash:ey,limits:{...Te}}}function rI(e){let t=Ir(e,"Native check receipt contract");return Tr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Gt(t.expectedHash,"Native check expected contract hash"),beforeHash:Gt(t.beforeHash,"Native check before contract hash"),afterHash:Gt(t.afterHash,"Native check after contract hash")}}function iI(e){let t=Ir(e,"Native check receipt implementation");return Tr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Gt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Gt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Gt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Gt(t.afterSnapshotHash,"Native check after snapshot hash")}}function nI(e,t){let r=Ir(e,`Native check batch ${t}`);Tr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Be(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Be(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Be(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Be(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Be(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Be(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Te.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Te.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function aI(e){let t=Ir(e,"Native check receipt counts");Tr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Be(t.filesSelected,"Native check filesSelected"),filesScanned:Be(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Be(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Be(t.bytesScanned,"Native check bytesScanned"),issueCount:Be(t.issueCount,"Native check issueCount"),recordedIssueCount:Be(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(nI):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Te.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Te.maxFiles||r.bytesScanned>Te.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function oI(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||ty.indexOf(e.kind)-ty.indexOf(t.kind)}function sI(e){if(!Array.isArray(e)||e.length>Te.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Ir(i,`Native check issue ${n}`);if(Tr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!Q_.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:eI(a.path,`Native check issue ${n} path`),line:ny(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(oI);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function cI(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!Z_.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=iy.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function lI(e){return j(Y_,e)}function ay(e){let t=Ir(e,"Native check receipt");if(Tr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Zw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!U_.test(t.change))throw new Error("Native check receipt change name is invalid");let r=ny(t.sourceRevision,"Native check source revision"),i=tI(t.checker),n=rI(t.contract),a=iI(t.implementation),o=lI({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Gt(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=ry(t.startedAt,"Native check receipt startedAt"),c=ry(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=aI(t.counts),u=sI(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=cI(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Te.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Te.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:Zw,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Gt(t.receiptHash,"Native check receipt content hash");if(j(J_,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var Zw,J_,nn,Qd,Te,G_,U_,K_,Y_,X_,ey,Q_,ty,iy,Z_,Zd=A(()=>{"use strict";pe();Zw="comet.native.check-receipt.v1",J_="comet.native.check-receipt.v1",nn="scoped-text-safety",Qd=1,Te=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),G_=/^[a-f0-9]{64}$/u,U_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,K_="comet.native.checker-policy.v1",Y_="comet.native.check-input.v1",X_=2048,ey=j(K_,{policy:nn,version:Qd,limits:Te,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Q_=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),ty=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],iy=["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"],Z_=new Set(iy)});function an(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function jr(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Ut(e,t){if(typeof e!="string"||!fI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Ke(e).trim();if(!r||r.length>vI||r!==e.trim())throw new Error(`${t} is invalid`);return r}function ef(e,t){let r=pt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function ja(e,t,r=pt,i=!1,n=gI){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function yI(e,t){if(typeof e!="string"||!pI.test(e))throw new Error(`${t} is invalid`);return e}function NI(e){let t=an(e,"Native verification receipt bindings");if(jr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!hI.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Ut(t.contractHash,"Native verification receipt contract hash"),scopeHash:Ut(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Ut(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Ut(t.artifactHash,"Native verification receipt artifact hash")}}function bI(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=mI.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function kI(e,t,r,i){let n=an(t,`Native ${e} evidence`);if(e==="automated-check"){if(jr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ef(n.startedAt,"Native automated-check start time"),o=ef(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=an(n.worktree,"Native automated-check worktree");if(jr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=an(n.afterFence,"Native automated-check after fence");if(jr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:pt(n.executable,"Native automated-check executable"),args:ja(n.args,"Native automated-check arguments",pt,!0),cwd:pt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:pt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Ut(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Ut(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Ut(n.outputHash,"Native automated-check output hash"),outputSummary:pt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){jr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=bI(n.checkReceiptRef);if(Ut(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:ja(n.subjects,"Native static inspection subjects",pt,i==="required-check"),rule:pt(n.rule,"Native static inspection rule"),resultSummary:pt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:ja(n.steps,"Native manual evidence steps"),observations:ja(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function SI(e){let t=an(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=pt(t.actor,"Native verification receipt actor"),o=ja(t.acceptanceIds,"Native receipt acceptance IDs",yI,i==="required-check",wI).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:tf,kind:r,role:i,status:n,bindings:NI(t.bindings),acceptanceIds:o,actor:a,issuedAt:ef(t.issuedAt,"Native verification receipt issue time"),evidence:kI(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==nn||s.actor!==`native-runtime:${nn}`))throw new Error("Native required check policy identity is invalid");return s}function oy(e){let t=an(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==tf)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=SI(i),a=Ut(t.receiptHash,"Native verification receipt hash");if(j(uI,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function rf(e){return j(dI,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var tf,uI,dI,fI,pI,hI,mI,vI,gI,wI,$a=A(()=>{"use strict";pe();Zd();ti();tf="comet.native.verification-receipt.v3",uI=tf,dI="comet.native.declared-artifacts.v1",fI=/^[a-f0-9]{64}$/u,pI=/^acceptance-[a-f0-9]{64}$/u,hI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,vI=4096,gI=256,wI=1024});import{createHash as EI}from"node:crypto";import{promises as ht}from"node:fs";import _t from"node:path";function nf(e,t){let r=_t.relative(e,t);return r===""||!_t.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_t.sep}`)}function CI(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ic(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function sy(e){let t=await ht.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ht.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function xI(e,t){let r=_t.resolve(e),i=_t.resolve(t);if(!nf(r,i))throw new Error("Native evidence path is outside its change");let n=[await sy(r)],a=r;for(let o of _t.relative(r,i).split(_t.sep).filter(Boolean)){a=_t.join(a,o);let s=await sy(a);if(!nf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function cy(e){for(let t of e){let r=await ht.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!CI(t,r)||await ht.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function PI(e,t,r={}){let i=await xI(t,_t.dirname(e));await r.afterParentChainCaptured?.();let n=await ht.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ht.realpath(e);if(!nf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ht.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ht.lstat(e),ht.realpath(e)]);if(await cy(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ic(s,n)||!ic(s,c))throw new Error("Native evidence document changed while opening");if(s.size>on)throw new Error(`Native evidence document exceeds ${on} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=on+1-d,g=await o.read(f,0,Math.min(f.length,m),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>on)throw new Error(`Native evidence document exceeds ${on} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),ht.lstat(e),ht.realpath(e)]);if(await cy(i),!v.isFile()||v.isSymbolicLink()||h!==a||!ic(s,p)||!ic(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function dy(e,t){if(!uy.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function RI(e,t,r,i,n){if(!uy.test(r))throw new Error("Native report evidence hash is invalid");let a=await ci({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||EI("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function sn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function AI(e,t,r,i,n){let a=dy(r,i);return n?_t.join(n,...a.split("/")):wr(K(e,t),a)}async function ci(e){let t=AI(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??me(e.paths,t);return await G(r,t),PI(t,r,e.hooks)}function ly(e,t){return Qs(e,t)}function _I(e,t){let r=Zs(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function II(e,t,r){let i=Xw(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function TI(e,t,r){let i=Xd(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function jI(e,t,r,i=!1,n){let a=await nc(e,t,r.implementationScopeRef,void 0,n);if(i&&await RI(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await fy(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Oa(e,t,r,i,n){let a=sn(r,"scopes"),o=_I(await ci({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=sn(o.baselineProjectionRef,"snapshots"),c=sn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ci({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ly(d,s)),ci({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ly(d,c))]);return Ww({baseline:l,current:u,scope:o})}async function nc(e,t,r,i,n){return(await Oa(e,t,r,i,n)).scope}async function fy(e,t,r,i,n){let a=sn(r,"allowances");return II(await ci({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Ha(e,t,r,i,n){let a=sn(r,"receipts"),o=oy(await ci({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function cn(e,t,r,i,n){let a=sn(r,"verifications"),o=TI(await ci({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await jI(e,t,o,!1,n),o}var uy,on,NF,$r=A(()=>{"use strict";se();Y();Nt();si();rc();$a();uy=/^[a-f0-9]{64}$/u,on=oi,NF=3*on});vt();pe();ge();We();import Qt from"node:path";import{realpathSync as u$}from"node:fs";import{promises as qj}from"fs";Gr();ge();it();Ct();Y();import{promises as gd}from"fs";import Mg from"path";var Wg=["outcome","scope","nonGoals","acceptanceExamples"],SA=[...Wg,"constraints","decisions","openQuestions","verificationExpectations"],EA=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],zg={maxFileBytes:Kn};function Jg(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
170
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function CA(e,t){let r=Mg.resolve(e,...t.split(/[\\/]/u));if(!F(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await gd.realpath(e),n=await gd.realpath(r);if(!F(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await gd.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Na(e){return{valid:e.length===0,findings:e}}function Gg(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function wd(e,t){let r=[],i;try{i=(await ae({root:e,ref:t,maxBytes:zg.maxFileBytes})).text}catch(a){return Na([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jg(i))n.set(Uo(a)??a,o);for(let a of SA)n.has(a)||r.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of Wg)(n.get(a)??"").length===0&&r.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return Gg(i)&&r.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Na(r)}async function yd(e,t){let r=[],i;try{i=(await ae({root:e,ref:t,maxBytes:zg.maxFileBytes})).text}catch(a){return Na([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jg(i))n.set(Um(a)??a,o);for(let a of EA)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Na(r)}function Vs(e,t){return Mg.join(e.specsDir,t,"spec.md")}async function Ug(e,t){let r=[],i=ye(e,t.name);for(let n of t.spec_changes){let a=Vs(e,n.capability),o=null;try{await G(e.nativeRoot,a),o=await Uu(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await CA(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Na(r)}na();pe();ge();it();na();pe();import Kg from"node:path";var xA="comet.native.contract.v1",PA="comet.native.acceptance-set.v1",Yg=/^[a-f0-9]{64}$/u,ba={maxAcceptanceCriteria:ia.maxCriteria};function Xg(e,t){let r=Kg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Kg.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Qg(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
171
- `))}function RA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Yg))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Yg))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Xg(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Qg(e.markdown)},markdown:e.markdown}}function AA(e,t){return Zg(e.id,t.id)}function Zg(e,t){return e<t?-1:e>t?1:0}function ew(e){let t=Xg(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(RA).sort((d,f)=>Zg(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=$u(e.briefMarkdown,t,ba.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Ou(f,d.source,ba.maxAcceptanceCriteria-a.length)),a.push(...wv(f,d.source,ba.maxAcceptanceCriteria-a.length)));if(a.sort(AA),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>ba.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${ba.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Qg(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(PA,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(xA,u)}}var Fs={maxSpecs:64,maxFileBytes:Kn,maxTotalBytes:4*1024*1024};async function Xi(e){if(e.specChanges.length>Fs.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ae({root:e.changeDir,ref:e.briefRef,maxBytes:Fs.maxFileBytes}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ae({root:e.changeDir,ref:n.source,maxBytes:Fs.maxFileBytes});if(r+=a.size,r>Fs.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:ew({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Zn();import _A from"path";var Nd="comet.selection.v2",IA=16*1024;function rw(e){return _A.join(e,".comet","current-change.json")}function TA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tw(e){return e===null||typeof e=="string"}function jA(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(!TA(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&&!tw(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Nd,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Nd)throw new Error(`current change selection schema must be ${Nd}`);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(!tw(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 iw(e){let t;try{let i=rw(e),{bytes:n}=await Pi(i,IA,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...jA(t)}}ge();We();ct();vt();se();import{promises as OI}from"node:fs";import af from"node:path";it();pe();Ea();Sa();ge();Ed();yr();ds();ka();Ms();se();aa();import{promises as h_}from"node:fs";import Sw from"node:path";function Us(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ks(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 Pt(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 Ew(e,t){return e===null?null:Pt(e,t)}function Xs(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 m_(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 v_(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Ys(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Bd(e,t){if(e===null)return null;let r=Pt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Ld(e,t){let r=Pt(e,t);if(!Sw.isAbsolute(r))throw new Error(`${t} must be absolute`);return Sw.resolve(r)}function g_(e,t){let r=`Native local checks[${t}]`,i=Us(e,r);if(Ks(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)=>Pt(l,`${r}.argv[${u}]`,!0)),a=Ys(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Bd(i.startedAt,`${r}.startedAt`),s=Bd(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=Xs(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Pt(i.id,`${r}.id`),name:Pt(i.name,`${r}.name`),operationId:Pt(i.operationId,`${r}.operationId`),status:a,repeatable:v_(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Xs(i.executionCount,`${r}.executionCount`),argv:n,cwd:Ld(i.cwd,`${r}.cwd`),exitCode:m_(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Pt(i.log,`${r}.log`)}}function w_(e){let t="Native local execution state",r=Us(e,t);if(Ks(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ss)throw new Error(`Native local execution schema must be ${ss}`);let i=Us(r.workspace,"Native local workspace");Ks(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Us(r.execution,"Native local execution");Ks(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Bd(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Pt(o.operationId,"Native local execution.operationId"),stage:Ys(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Ys(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ew(o.executionId,"Native local execution.executionId"),status:Ys(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Xs(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(g_);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:ss,change:Pt(r.change,"Native local change"),basedOnStateVersion:Xs(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ld(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ld(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ew(i.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Cw(e){let t;try{t=await h_.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return w_(r)}ct();Hu();yr();Wu();ds();ka();Ms();se();Gr();ka();Y();Gr();$r();We();var HI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DI="comet-state.yaml",BI="state.json",Cq=Ko("en");function py(e,t){if(!HI.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=af.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}function hy(e,t){return af.join(py(e,t),DI)}function LI(e,t){return af.join(gr(e,t),BI)}async function of(e,t){try{let r=await OI.readFile(hy(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function my(e,t){return Dt(hy(e,t))}async function vy(e){let t=await my(e.paths,e.name),r=LI(e.paths,e.name);try{let i=await Cw(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var Oq=16*1024;async function gy(e){let t=await iw(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Bs(t.selection.change),t.selection)}Gi();Y();Zr();Is();async function wy(e,t){let r=[],i=K(e,t.name),n=wr(i,Ue.stateRef),a;try{a=await Ki(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=wr(i,a.trajectoryRef),s=await kg(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Qr(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=wr(i,a.checkpointRef);try{let u=await _s(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Ji();Gi();se();ge();Ct();ra();ct();Y();st();ti();import oT from"path";import{isDeepStrictEqual as hf}from"util";pe();pe();var ln={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var VI=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function FI(e,t){return e<t?-1:e>t?1:0}function qI(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!VI.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(FI)}function sf(e=[]){return qI(e,"Native repair failed check IDs",ln.maxFailedCheckIds,!0)}function yy(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function MI(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:yy(e.failedAcceptanceIds,t.failedAcceptanceIds)&&yy(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function cf(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(MI(i,a))break;r+=1,i=a}return r}rc();si();function lf(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var Ny="repairStagnation",Le={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},zI=/^[a-f0-9]{64}$/u;var JI=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),GI=["data","runId","sequence","timestamp","type"],by=["disposition","overrideSummaryHash","signatureHash"],UI=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],ky=12;function df(e,t){return e<t?-1:e>t?1:0}function Sy(e,t,r){let i=Object.keys(e).sort(df);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Da(e,t){if(typeof e!="string"||!zI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function KI(e){if(!Array.isArray(e)||e.length>ln.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(df)}function Ey(e){if(typeof e!="string"||e.length===0||e.length>Le.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function uf(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Le.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Le.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Le.maxTextCharacters&&(!n||e.length>Le.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Le.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Le.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>uf(s,t+1,r,`${i}[${c}]`));return}let a=ac(e,i),o=Object.keys(a);if(o.length>Le.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Le.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Le.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");uf(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function YI(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function XI(e,t,r){let i=ac(e,`Native repair trajectory event ${t+1}`);if(Sy(i,GI,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(YI(i.timestamp),typeof i.type!="string"||!JI.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(Ey(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return uf(i.data,0,n,"Native trajectory event data"),ac(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function ff(e){let t=ac(e,"Native repair trajectory projection"),r=Object.keys(t).sort(df),i=r.length===by.length&&r.every((l,u)=>l===by[u]);i||Sy(t,UI,"Native repair trajectory projection");let n=Da(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Da(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Da(t.contractHash,"Native repair trajectory contract hash"),s=KI(t.failedAcceptanceIds),c=sf(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function QI(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function ZI(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??ky;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=cf({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<ln.warningAtConsecutiveFailures?"continue":a<ln.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function eT(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??ky;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Cy(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Le.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Ey(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=XI(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Le.maxTotalDataNodes||c>Le.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Da(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Da(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Ny)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=ff(f[Ny]);if(QI(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(r.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),ZI(v,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");eT(v,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(i=v,r.length>ln.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function xy(e){return Cy(e).history}function Py(e){let t=Cy(e).latestProjection;return t?{...t}:null}Ct();var un={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:[]},pf=X("comet-native-runtime:v3:scope-reopen"),tT=[{skillVersion:"3",skillHash:X("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:X("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:X("comet-native-runtime:v1")}];function Ry(e){return e.skillVersion===un.definition.metadata.version&&e.skillHash===pf||tT.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Zr();Ct();Zr();Ct();function Ay(e){return X(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}Is();fs();var $y=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],sT=new Set($y),Oy=new Set([...$y,"minimum_runtime_version","revision"]),cT=new Set([...Oy,"operation"]),lT=512*1024,mf=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),uT=new Set([...mf,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),vf=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function wf(e,t){return oT.join(K(e,t),"transition.json")}function sc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function yf(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function oc(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!uT.has(u)),a=[...mf].find(u=>!Object.hasOwn(r,u)),o=mf.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(lf(r.summary,"Native transition journal event summary"),Ke(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(lf(r.noCodeReason,"Native transition journal event no-code reason"),Ke(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?ff(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function dT(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return gf({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return gf(e,t)}function Nf(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?dT(e.eventData,e.evidenceHash):gf(e.eventData,e.evidenceHash),n=sd(e.nextRun),a=e.previousRun===null?null:sd(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function _y(e,t,r=!1){if(e.skill!==un.definition.metadata.name||(r?!Ry(e):e.skillVersion!==un.definition.metadata.version||e.skillHash!==pf)||e.orchestration!==un.definition.orchestration.mode||e.pendingRef!==Ue.pendingRef||e.trajectoryRef!==Ue.trajectoryRef||e.contextRef!==Ue.contextRef||e.artifactsRef!==Ue.artifactsRef||e.checkpointRef!==Ue.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Iy(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ty(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function bf(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(_y(o,"next Run",i||a!==null),Ty(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(_y(a,"previous Run",!0),Ty(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!hf(Iy(a),Iy(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function fT(e,t,r){return X(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function Hy(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function jy(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function kf(e,t,r,i,n=!1){let a=r.eventData,o=jy(e),s=jy(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&hf(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&hf(e.spec_changes,t.spec_changes),l=Ay({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(i==="spec-rebase"){let c=fT(e.name,a.summary,t.spec_changes),l=X(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function pT(e,t){let r=sc(e);if(yf(r,cT),r.schema!==Di)throw new Error(`Expected Native transition schema ${Di}`);let i=oc(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Di} minimum_runtime_version must be ${3}`);let n=oc(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Nf(r,t),o=Sr(r.previousState),s=Sr(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(kf(o,s,a,r.operation),bf(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Di,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function hT(e,t){let r=sc(e);if(yf(r,sT),r.schema!==sa)throw new Error(`Expected Native transition schema ${sa}`);let i=Nf(r,t,!0),n=Li(r.previousState),a=Li(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return kf(n,a,i,Hy(n,a,i.eventData),!0),bf(n,a,i,!0),{schema:sa,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function mT(e,t){let r=sc(e);if(yf(r,Oy),r.schema!==Bi)throw new Error(`Expected Native transition schema ${Bi}`);if(oc(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Bi} minimum_runtime_version must be 2`);let n=oc(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Nf(r,t,!0),o=Vi(r.previousState),s=Vi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(kf(o,s,a,Hy(o,s,a.eventData),!0),bf(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Bi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function vT(e,t){let r=sc(e);if(r.schema===Di)return{status:"current",journal:pT(r,t)};if(r.schema===sa)return{status:"migration-required",journal:hT(r,t)};if(r.schema===Bi)return{status:"migration-required",journal:mT(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function gT(e,t){let r=wf(e,t),i=me(e,r);await G(i,r);try{let n=await Bt({root:i,file:r,maxBytes:lT,label:`Native transition journal ${t}`});return vT(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Dy(e,t){let r=await gT(e,t);if(!r)return null;if(r.status==="migration-required")throw new vf(t);return r.journal}xr();var wT=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function yT(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function NT(e){return e?e.map(yT).join(" "):null}function bT(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function Ye(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function kT(e){return e.map(t=>Ye(t,[],null))}function ST(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[Ye("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(Ye("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(Ye("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Ye("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(Ye("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(Ye("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Ye("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ke(e,t){let r=t.commandArgs===void 0?bT(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?NT(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??kT(t.requiredInputs??[])}}function cc(e){let r=(e.findings??[]).filter(d=>!Yi(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||wT.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Ye("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Ye("summary",["--summary"],"<summary>")]});if(n)return ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Ye("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Ye("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=ST(e.state);return ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}ge();Y();xr();import Ba from"path";var By=8,ET={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function CT(e){let t=ET[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Yi(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function xT(e,t,r){if(!r.path)return null;let i;if(Ba.isAbsolute(r.path)?i=Ba.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Ba.resolve(ye(e,t.name),...r.path.split(/[\\/]/u)):i=Ba.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!F(e.projectRoot,i))return null;let n=Ba.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function PT(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Sf(e){return e.findings.map(t=>{let r=CT(t.code);return{code:t.code,message:t.message,severity:r.severity,path:xT(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:PT(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function Ef(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,By),truncated:t.length>By}}se();ge();Ct();Y();st();Gn();ti();import dn from"path";var Hr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},fn=/^[a-f0-9]{64}$/u;function lc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function uc(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Or(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function Ly(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Cf(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function RT(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||dn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=dn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Vy(e,t){return dn.join(K(e,t),"checkpoints","progress.json")}function La(e,t){return dn.join(K(e,t),"checkpoint-journal.json")}function Fy(e,t,r){if(!fn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return dn.join(K(e,t),"checkpoints","manifests",`${r}.json`)}function AT(e){if(!fn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function xf(e,t,r){let i=await Bt({root:e,file:t,maxBytes:Hr.maxDocumentBytes,label:r});return JSON.parse(i.bytes.toString("utf8"))}function _T(e,t){let r=lc(e,`checkpoint manifest artifact ${t}`);uc(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=RT(Or(r.path,`checkpoint artifact ${t} path`,4096)),n=yt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!fn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Cf(r.size,`checkpoint artifact ${t} size`)}}function Pf(e,t){let r=lc(e,"Native checkpoint manifest");if(uc(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Hr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(_T),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Cf(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Hr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function qy(e){return X(JSON.stringify(Pf(e,e.change)))}function My(e,t){let r=lc(e,"Native progress checkpoint");if(uc(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Ly(r.previousRevision,"Native checkpoint previousRevision"),a=Ly(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Or(r.manifestHash,"Native checkpoint manifestHash",64);if(!fn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=AT(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Or(r.inputHash,"Native checkpoint inputHash",64);if(!fn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Or(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Cf(r.artifactCount,"Native checkpoint artifactCount");if(u>Hr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Or(r.summary,"Native checkpoint summary"),f=Or(r.nextAction,"Native checkpoint nextAction");if(Ke(d)!==d||Ke(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Or(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function IT(e,t){let r=lc(e,"Native checkpoint journal");if(uc(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Sr(r.previousState),n=Sr(r.nextState),a=My(r.checkpoint,t),o=Pf(r.manifest,t),s=Or(r.inputHash,"Native checkpoint journal inputHash",64),c=X(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!fn.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==qy(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function TT(e,t,r){let i=dn.resolve(e.projectRoot,...t.split("/"));if(!F(e.projectRoot,i)||F(e.nativeRoot,i)||F(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=cu(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Bt({root:e.projectRoot,file:i,maxBytes:Hr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function jT(e,t){let r=Vy(e,t),i=me(e,r);await G(i,r);try{return My(await xf(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function $T(e,t,r){let i=Fy(e,t,r),n=me(e,i);await G(n,i);let a=await xf(n,i,"Native checkpoint manifest"),o=Pf(a,t);if(Wy(e,o),qy(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Rf(e,t){let r=La(e,t),i=me(e,r);await G(i,r);try{let n=IT(await xf(i,r,"Native checkpoint journal"),t);return Wy(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Wy(e,t){for(let r of t.artifacts){let i=cu(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function zy(e){let t;try{t=await jT(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Vy(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await $T(e.paths,e.name,t.manifestHash);let a=X(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await TT(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fy(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Jy=240,Gy=8,dc=50;function Uy(e){let t=Array.from(e);return t.length<=Jy?e:`${t.slice(0,Jy-1).join("")}…`}function OT(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function HT(e){let t=[...new Set(e.map(OT))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Gy),reasonCount:e.length,codesTruncated:t.length>Gy};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,dc),reasonsTruncated:e.length>dc}}}async function Ky(e){let t=null;try{let s=await Rf(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:La(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:La(e.paths,e.state.name)}}let r=await zy({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=HT(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Hr.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:Uy(r.checkpoint.summary),nextAction:Uy(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Hr.maxArtifacts}}import{promises as Oj}from"node:fs";import hN from"node:path";pe();import Yy from"node:path";var DT="comet.native.archive-preflight.v1",BT="comet.native.archive-preflight.v1",LT="comet.native.archive-operation.v1",VT=/^[a-f0-9]{64}$/u,Xy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function fc(e,t){return e<t?-1:e>t?1:0}function qT(e,t){if(typeof e!="string"||!VT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Kt(e,t){return e===null?null:qT(e,t)}function MT(e,t){let r=Yy.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Yy.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function WT(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function zT(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function JT(e,t){if(!Xy.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=Kt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=Kt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Kt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function GT(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Kt(e.contractHash,"Native archive contract hash"),acceptanceHash:Kt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Kt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Kt(e.reportHash,"Native archive report hash"),envelopeHash:Kt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Kt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function UT(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!FT.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(fc);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function KT(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(fc)}function Qy(e){if(!Xy.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(JT).sort((l,u)=>fc(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:j(LT,l)})),i=GT(e.evidence),n=zT(e.workspace),a=[...new Set([...UT(e.findingCodes??[]),...KT({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(fc),o=WT(e.revision),s=MT(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:DT,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:j(BT,c)}}it();ge();pe();import{createHash as YT}from"node:crypto";import Zy from"node:path";var XT="comet.native.conflict-radar.v1",je=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}),QT="comet.native.conflict-radar.v1",ZT="comet.native.conflict-radar-signals.v1",ej=/^[a-f0-9]{64}$/u,rN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tj=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),rj=new Set(["capability","operation","baseHash"]),ij=new Set(["path","kind"]);function pn(e,t){return e<t?-1:e>t?1:0}function Af(e){return Buffer.byteLength(e,"utf8")}function _f(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function If(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Af(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function nj(e,t){let r=If(e,t,je.maxArtifactPathBytes),i=Zy.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Zy.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function iN(e,t){if(typeof e!="string"||!ej.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function aj(e,t){let r=_f(e,rj,t),i=If(r.capability,`${t} capability`,je.maxCapabilityBytes);if(!rN.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:iN(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function oj(e,t){let r=_f(e,ij,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:nj(r.path,`${t} path`),kind:r.kind}}function sj(e,t){let r=_f(e,tj,`Conflict radar change ${t}`),i=If(r.name,`Conflict radar change ${t} name`,je.maxNameBytes);if(!rN.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>je.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>je.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>aj(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>pn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>oj(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>pn(c.path,l.path)||pn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:iN(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function cj(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>je.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(sj).sort((n,a)=>pn(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>je.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>je.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function lj(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function uj(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function dj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function fj(e,t){let r=[],i=YT("sha256").update(`${ZT}
172
- [`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(vn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<je.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(lj(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=uj(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:dj(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function eN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function pj(e,t){return eN(e.classification)-eN(t.classification)||pn(e.left,t.left)||pn(e.right,t.right)}function tN(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:XT,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function nN(e){let t=cj(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(fj(t[s],t[c]));r.sort(pj);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(QT,{changes:t,relationships:i}),a=r.slice(0,je.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=tN(t,r,a,n);for(;a.length>0&&Af(JSON.stringify(o))>je.maxSerializedBytes;)a=a.slice(0,-1),o=tN(t,r,a,n);if(Af(JSON.stringify(o))>je.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}$r();st();xr();var hj=4096;async function mj(e,t=je.maxChanges){try{let r=await ca({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function aN(e,t){let r=await Mt(e,t),[i,n]=await Promise.all([r.implementation_scope?nc(e,t,r.implementation_scope):null,Ft(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function pc(e,t,r={}){let n=(await mj(e,hj)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await aN(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await aN(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=nN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}ge();We();Y();na();it();ge();$r();Ji();si();rc();import{execFile as xj}from"node:child_process";qs();Sd();ge();import{promisify as Pj}from"node:util";ge();ct();se();Zd();Y();Nt();import{constants as Tf,promises as Xe}from"node:fs";import hn from"node:path";var gj=/^[a-f0-9]{64}$/u,wj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Va=512*1024;function yj(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Nj(e,t){let r=hn.resolve(e),i=hn.resolve(t);if(!F(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...hn.relative(r,i).split(hn.sep).filter(Boolean)]){o&&(a=hn.join(a,o));let s=await Xe.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Xe.realpath(a);if(n.length>0&&!F(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function sN(e){for(let t of e){let r=await Xe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!yj(t,r)||await Xe.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function bj(e){if(!gj.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function kj(e){let t=wj.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function Sj(e,t,r){return wr(K(e,t),bj(r))}async function Ej(e,t,r){let i=await Nj(r,hn.dirname(e)),n=await Xe.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Va)throw new Error(`Native check receipt exceeds ${Va} bytes`);let[a,o]=await Promise.all([Xe.realpath(t),Xe.realpath(e)]);if(!F(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Tf.O_RDONLY|Tf.O_NOFOLLOW|Tf.O_NONBLOCK,c=await Xe.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Xe.lstat(e),Xe.realpath(e)]);if(await sN(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!hc(n,l)||!hc(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let b=Va+1-p,S=await c.read(v,0,Math.min(v.length,b),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>Va)throw new Error(`Native check receipt exceeds ${Va} bytes`);f.push(Buffer.from(v.subarray(0,S.bytesRead)))}let[h,m,g]=await Promise.all([c.stat(),Xe.lstat(e),Xe.realpath(e)]);if(await sN(i),!m.isFile()||m.isSymbolicLink()||g!==o||!F(a,g)||!hc(l,h)||!hc(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function cN(e,t,r){let i=kj(r),n=K(e,t),a=Sj(e,t,i),o=me(e,a);await G(o,a);let s=ay(await Ej(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}$r();ct();ti();var Fa=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Ji();$a();si();var JW=64*1024;var GW=3600*1e3;var UW=Pj(xj);var Rj=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function lN(e,t){let r=[];for(let i of Rj){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function uN(e){if(e.receipt.kind!=="static-inspection")return null;let t=await cN(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}$a();var Dr=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}};function Aj(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function _j(e){let t=Aj(e.bundle.baseline),r=await nd(e.paths,t,{origin:"explicit",now:e.now});return Gd({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function fN(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Oa(e.paths,e.state.name,e.state.implementation_scope),r=await Xi({changeDir:ye(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await _j({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function pN(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await fN(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function Ij(e){let t=await ae({root:ye(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Nv(t.text)}}function Tj(e){let{receipt:t,implementationScope:r}=e,i=[],n=Jd({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function jj(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:rf(e.implementationScope.scope.declaredArtifacts)}}async function dN(e){let t=await Ha(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=lN(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new Dr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await uN({paths:e.paths,state:e.state,receipt:t});if(n){let a=Tj({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function $j(e){let t=jj({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await dN({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Dr)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await dN({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Dr)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new Dr(r)}function jf(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function $f(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:jf(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([fN(e),cn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:jf(e.state.verification_result,"stale"),envelope:null};let i=await Ij({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await $j({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:jf(e.state.verification_result,"invalid"),envelope:null}}}xr();function Hj(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function mN(e){try{return await Oj.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dj(e,t){try{return(await ae({root:e,ref:t})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Bj(e,t,r){let i=Vs(e,r.capability);if(!F(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=hN.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await Dj(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ae({root:ye(e,t),ref:r.source})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function Lj(e,t){return mN(wf(e,t))}async function Of(e){let t=e.now??new Date,r=await Mt(e.paths,e.name),i=await Ft(e.paths,e.name),n=await Ae(e.paths.projectRoot),a=Hj(r.name,t),o=hN.resolve(e.paths.nativeRoot,...a.split("/"));if(!F(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(r.spec_changes.map(v=>Bj(e.paths,r.name,v))),$f({paths:e.paths,state:r,now:t}),pc(e.paths,r.name),Ls(e.paths,r.name),Vg(e.paths,r.name),Lj(e.paths,r.name),mN(o)]);return Qy({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}Y();$r();Zr();$a();si();async function Vj(e,t){let r=K(e,t.name),i=await Ki(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await _s(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Qr(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function Fj(e,t){let r=await Vj(e,t);return{committed:r,latest:Py(r),history:xy(r)}}async function vN(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await Fj(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}$r();xr();st();Y();var Yt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Mj(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function Wj(e){return(await gy(e))?.change??null}function zj(e,t,r=!1,i){return cc({state:e,archiveReady:t,evidenceRetreat:r}).command}async function Jj(e,t){let r=ye(e,t.name),i=[...(await wd(r,t.brief)).findings,...(await Ug(e,t)).findings,...await wy(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ss(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await ig(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Xi({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Dy(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await yd(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function Hf(e,t,r){let i=await Wj(e)===t,n=await Ru(e,t),a=await ma(e,t),o;try{let y=await vd(e,t);if(y.status==="migration-required"&&y.state)return{name:t,phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Sf({paths:e,state:o,findings:[y]}),O=cc({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:Ef(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await Ky({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await vN(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await Xi({changeDir:ye(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let de=await cn(e,o.name,o.verification_evidence);for(let ee of de.acceptanceTrace.entries)C.set(ee.acceptanceId,ee.status==="failed"?"failed":ee.status==="missing"?"missing":"satisfied")}let O=gv({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),$=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...$?{nextPageCommand:Mj($),nextPageArgs:$}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await pc(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let y=await Ft(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await va({paths:e,identity:y});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await $s({paths:e,identity:y});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let y=await pN({paths:e,state:o});v=y.freshness!=="fresh",p.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Of({paths:e,name:o.name}),m.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await Jj(e,o),...s.findings,...d,...f,...p,...l,...m].filter((y,C,O)=>O.findIndex($=>$.code===y.code&&$.path===y.path)===C),b=Sf({paths:e,state:o,findings:g}),S=b.filter(y=>!Yi(y.code)),w=o.phase==="archive"&&h?.ready===!0&&S.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),k=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=b.find(y=>y.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:k||x?null:zj(o,w,E,r?.clarificationMode),archiveReady:w,inspection:s.inspection,findingSummary:Ef(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:cc({state:o,findings:b,archiveReady:w,evidenceRetreat:E,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:dc,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function gN(e){let t;try{t=await Gu({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await qj.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Yt.maxChanges))throw new Error(`Native status exceeds ${Yt.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}Y();var Bf=fi(Jr(),1);Qi();pe();it();yr();import{promises as Gj}from"node:fs";import Df from"node:path";var mc=class extends Error{};async function Lf(e,t){let r=await ae({root:e.nativeRoot,ref:Df.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:4194304,includeHash:!1}),i=(0,Bf.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new mc("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:_e(i)}}async function yN(e,t){let r;try{r=await Gj.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}if(r.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=Df.join(e.archiveDir,n.name,"comet-state.yaml");try{let o=await Lf(e,a);o.state.archived&&o.state.status==="done"&&i.push(o)}catch(o){if(o.code==="ENOENT"||o instanceof mc)continue;let s=n.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(s,`Native archive ${n.name} is unreadable: ${o.message}`)}}return i}function vc(e){return j("comet.native.status-record.v1",e)}function wN(e){let t=Df.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=Wt(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=_e((0,Bf.parse)(Wt(e.projectRoot,["show",`${r}:${t}`])));return vc(i)===vc(e.state)?r:null}catch{return null}}function NN(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=wN(e),i=wN(t);if(!r||!i)return!1;try{return Wt(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function bN(e,t){return e.state.archived&&t.state.archived&&vc(e.state)===vc(t.state)}vt();Ea();Sa();import AN from"node:path";Ea();pe();Sa();import{promises as kN}from"node:fs";import Uj from"node:path";var Kj=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),Yj=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),Xj=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Qj=new Set(["status","summary"]);function gc(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function wc(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function Zj(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function li(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function e$(e,t,r,i){let n=gc(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=wc(n,Kj,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=gc(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=wc(o,Yj,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=gc(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=wc(c,Qj,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=gc(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:v,...h}=f,m=wc(h,Xj,`Native Supervisor child ${u}`);if(m)return m;let g=r.children[u],b=g.covers.length>0?g.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(b)||v!==void 0&&v!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!Zj(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let S=g.depends_on.length===0?"ready":"pending";if(f.status!==S)return`Native Supervisor child ${g.name} has progressed beyond its initial ${S} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function SN(e){let t=zs(e.paths,e.state.name),r;try{let c=await kN.lstat(t);if(!c.isFile()||c.isSymbolicLink())return li(t,"","Native Supervisor overlay is not a regular file");r=await kN.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:li(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return li(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=Uj.join(e.paths.changesDir,e.state.name),a;try{a=await en({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return li(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Rr(e.paths,e.state.name)}catch(c){return li(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return li(t,r,"Native Supervisor overlay disappeared during inspection");let s=e$(i,e.state,a.contract,o);return s?li(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}aa();function Xt(e,t,r){return e.language==="zh-CN"?r:t}function t$(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:Xt(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:Xt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Xt(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(Xt(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(Xt(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(Xt(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 r$(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 i$(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:Xt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Xt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function CN(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ui(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function n$(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function EN(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function a$(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function o$(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 Br(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:CN({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ui("summary","--summary"),n$(e.name,e.flag)]}}function Vf(e){return[Br({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Br({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Ff(e,t,r={}){let i=a$(t)&&e.coordination_mode===void 0,n=t$(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:[ui("summary","--summary")],commandAlternatives:[Br({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:[ui("summary","--summary")],commandAlternatives:[Br({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Vf({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:[ui("summary","--summary")],commandAlternatives:[Br({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Br({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:[ui("summary","--summary")],commandAlternatives:[Br({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Vf({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:[ui("summary","--summary")],commandAlternatives:Vf({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?CN({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:o$({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?[EN("coordination-mode","--coordination-mode",bv)]:[]],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:[ui("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} ${Xt(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:[EN("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...i$(e)],userCommunication:r$(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Br({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")}}import xN from"node:path";function PN(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function qf(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:PN(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:PN(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>xN.relative(t.projectRoot,xN.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}function _N(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function IN(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function TN(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:c$(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:l$(i,r)}))]:[]]}function jN(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function RN(e,t){let r=Ee(e.projectRoot),i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:AN.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function Mf(e){let{state:t,paths:r}=e,i=qf(t),n=e.details?TN(t,null,[]):[],a=IN(e.cursor,t.state_version,0),o=n.slice(a,a+32),s=a+o.length<n.length?_N(t.state_version,0,a+o.length):null;return{schema:"comet.native.status.v2",name:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,archived:!0,archiveRef:AN.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:jN(t),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:i.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:Ff(t),...e.details?{details:{stateVersion:t.state_version,items:o,nextCursor:s,nextPageArgs:s?["comet","native","status",t.name,"--details","--cursor",s,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function s$(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function yc(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function c$(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:yc(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function l$(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:yc(e.summary,t)??""}}async function Wf(e){let t=await vy(e),r=qf(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Ca({paths:e.paths,state:t.state}),a=await SN({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Rr(e.paths,e.name,{diagnostics:!0}),s=o?{...RN(e.paths,t.state),projectRoot:"."}:RN(e.paths,t.state),c=Ff(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?s$(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:w})=>w==="pending"||w==="ready").length,h=o.children.filter(({status:w})=>w==="active"||w==="verified").length,m=o.children.filter(({status:w})=>w==="integrated"||w==="archived").length,g=o.children.filter(({status:w})=>w==="blocked"||w==="needs-reverify").length,b=o.children.filter(({status:w})=>w==="active"||w==="blocked"||w==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:yc(w.blocker,u)})),S=o.children.flatMap(({blocker:w})=>{let E=yc(w,u);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:g,active:b,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:m},risks:S,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":g>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=TN(t.state,o,u),m=IN(e.cursor,t.state.state_version,v),g=h.slice(m,m+32),b=m+g.length<h.length?_N(t.state.state_version,v,m+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:jN(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}xr();var d$=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Nc(e,t){let r=Qt.normalize(zf(e)),i=Qt.normalize(zf(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function zf(e){let t=Qt.resolve(e);try{return u$.native(t)}catch{return t}}function f$(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function $N(e){let t=[];for(let r of await gN(e))t.push({name:r,kind:await of(e,r)?"portable":"legacy"});return t}async function BN(e){let t=Qt.resolve(e),r=er(e),i=r.length>0?r:[t];i.some(o=>Nc(o,t))||i.push(t);let n=[],a=new Set;for(let o of i.map(s=>Qt.resolve(s)).sort()){let s=Nc(o,t)?t:o,c=zf(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Ae(s);if(!u)continue;let d=await Ot(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await $N(d)})}if(n.length===0){let o=await Ae(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await Ot(e,o.native.artifact_root);n.push({projectRoot:Qt.resolve(e),config:o,paths:s,changes:await $N(s)})}for(let o of n)o.archiveErrors=[],o.archives=await yN(o.paths,(s,c)=>o.archiveErrors.push({name:s,message:c}));return n}function ON(e,t){return e.workspace.bindingState==="aligned"?0:Nc(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function LN(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:u,kind:d})=>{if(d==="portable")try{let f=await Wf({paths:u.paths,name:n});return{source:u,name:n,kind:d,workspace:f.workspace,portableStatus:f,inspectionError:null}}catch(f){return{source:u,name:n,kind:d,workspace:await ma(u.paths,n),portableStatus:null,inspectionError:f instanceof Error?f.message:String(f)}}return{source:u,name:n,kind:d,workspace:await ma(u.paths,n),portableStatus:null,inspectionError:null}})),s=t.flatMap(u=>(u.archives??[]).filter(({state:d})=>d.name===n).map(d=>{let f=Mf({paths:u.paths,...d});return{source:u,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:null,record:d}})),c=t.flatMap(u=>(u.archiveErrors??[]).filter(d=>d.name===n).map(d=>({source:u,error:d})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}if(s.length>0){for(let d of o)if(d.kind==="portable")try{d.record=await Lf(d.source.paths,Qt.join(d.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let u=s.find(d=>[...o,...s.filter(f=>!bN(d.record,f.record))].every(f=>f.record&&NN(d.record,f.record)));if(u){i.push(u);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((u,d)=>ON(u,e)-ON(d,e)||u.source.projectRoot.localeCompare(d.source.projectRoot));let l=o.filter(u=>u.workspace.bindingState==="aligned");l.length>1?i.push(...l):l.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(l[0]??o[0])}if(i.length>Yt.maxChanges)throw new Error(`Native status discovery exceeds ${Yt.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function HN(e,t){let r=t.toString(36),i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function p$(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=d$.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function DN(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?f$(r):null,nextPageArgs:r}}async function h$(e,t,r){let i=null;try{i=await qg(e.source.paths,e.name)}catch{}return i?.state?{schema:"comet.native.status.v2",name:e.name,phase:i.state.phase,status:"blocked",migrationRequired:!0,legacySchema:i.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:i.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:Hf(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function VN(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:e.record?.state.archived?Mf({paths:e.source.paths,...e.record,details:t,cursor:i}):Wf({paths:e.source.paths,name:e.name,details:t,...i?{cursor:i}:{}})}return h$(e,t,r)}async function FN(e){let t=await BN(e.projectRoot),r=(await LN(e.projectRoot,t)).filter(i=>i.name===e.name);if(r.length===0){let i=t.find(n=>Nc(n.projectRoot,e.projectRoot))??t[0];return Hf(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}if(r.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${r.map(i=>i.source.projectRoot).join(", ")}`);return VN(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function qN(e){let t=await BN(e.projectRoot),r=await LN(e.projectRoot,t),i=j("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=p$({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+Yt.maxItems).map(u=>VN(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<r.length?HN(i,f):null,v={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...DN(Qt.resolve(e.projectRoot),p),limits:{...Yt}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Yt.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?HN(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...DN(Qt.resolve(e.projectRoot),l),limits:{...Yt}}}Zn();import qa from"path";import{realpathSync as T$}from"fs";vt();var Zt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function MN(e){return e?e.command?`${Zt.next} ${e.command}`:e.ask_user?`${Zt.next} ${e.ask_user}`:null:null}function WN(e,t){let r=[e.summary],i=MN(e.next);return i&&r.push(i),e.user_message&&r.push("",Zt.relay,e.user_message),t!==void 0&&r.push("",Zt.details,JSON.stringify(t,null,2)),`${r.join(`
168
+ `),e.omissionOverflow&&Ar(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(i+=1),n+=1,Ar(a,"omission",f)},s=f=>{i+=1,n+=1,Ar(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let p=r[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(f,1),p}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Ra(u)>oi;){if(r.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(r.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function qd(e){let t=Xr(e),r=t.entries.map((n,a)=>P_(n,`Snapshot entry ${a}`));if(r.sort(A_),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>R_(n,`Snapshot omission ${a}`));return i.sort(__),I_({schema:$w,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Aa(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:_r(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>be(r.path,i.path)||be(r.kind,i.kind))}function _a(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Pw(e){return e?{hash:e.hash,size:e.size}:null}function zd(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:be(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:Pw(c),after:Pw(l)})}}function Dw(e,t){return{...e,attributedTo:t.filter(r=>_a(r,e.path))}}function Jd(e){let t=Aa(e.declaredArtifacts),r=[];return zd(e.baseline,e.current,i=>{r.push(Dw(i,t))}),r}function Jt(e,t){return{id:`scope:${j(b_,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function T_(e,t){let r=t.omitted.map(i=>Jt({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(Jt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Jt({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function Rw(e,t){return T_(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Md(e,t){return be(e.kind,t.kind)||be(e.source,t.source)||x_(e.path,t.path)||be(e.id,t.id)}function j_(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Md)}function Bw(e){return[...new Set(e.map((t,r)=>_r(t,`Git path ${r}`)))].sort(be)}function Aw(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function $_(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Lw(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Bw(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Aw(e.baseCommit,"Native external drift base commit"),targetBranch:$_(e.targetBranch,"Native external drift target branch"),targetCommit:Aw(e.targetCommit,"Native external drift target commit"),paths:t}}function Vw(e){if(typeof e.contractHash!="string"||!Wd.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Aa(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Bw(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Lw(e.externalDrift)}}}function O_(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,f=0;return zd(e,t,p=>{let v=r.some(h=>_a(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<E_){let h=Dw(p,r),m=Ra(h);l+m<=oi?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Fw(e,t){return Jt({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function H_(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:tn(Number(t[1]),"Scope overflow change count"),unresolved:tn(Number(t[2]),"Scope overflow unresolved count"),unattributed:tn(Number(t[3]),"Scope overflow unattributed count")},i=ai(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Fw(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function D_(e){let t=jw("sha256");t.update(`${k_}
169
+ `);let r=0;zd(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Ar(t,"change",n);let a=0;for(let o of e.declaredArtifacts)_a(o,n.path)&&(a+=1,Ar(t,"change-attribution",o));Ar(t,"change-end",{attributionCount:a}),a===0&&Ar(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Ar(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function qw(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=O_(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),N=new Set(o.changePaths),y=r.externalDrift.paths.filter(C=>!N.has(C)||n.some(O=>_a(O,C)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j(xa,e),c=j(xa,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,N]of[["baseline",e],["current",t]])for(let y of N.omitted){if(l.length>=C_)break;l.push(Jt({kind:"snapshot-omission",source:x,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${x} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Rw("baseline",e),...Rw("current",t),...o.totalChanges===0&&a===null?[Jt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(N=>x.has(N)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(N=>!x.has(N))}},v=x=>{let N=o.candidates.slice(0,x.detailedChangeCount),y=N.filter(Ze=>Ze.attributedTo.length===0&&!u.has(Ze.path)),C=o.totalChanges-N.length,O=o.totalUnattributed-y.length,$=d-x.detailedOmissionCount,de=O+$,ee=[...y.map(Ze=>Jt({kind:"unattributed-change",source:"implementation-scope",path:Ze.path,evidence:{after:Ze.after,before:Ze.before,changeKind:Ze.kind}},`Changed path is not covered by a declared artifact: ${Ze.path}`)),...l.slice(0,x.detailedOmissionCount),...f,...de>0?[Fw(x.overflowHash,{changes:C,unattributed:O,unresolved:de})]:[]],U=j_(ee),vt=x.includeGitAdvisory?p():void 0;return{schema:Vd,contractHash:i,baselineProjectionRef:Fd(s),baselineProjectionHash:s,currentProjectionRef:Fd(c),currentProjectionHash:c,complete:U.length===0,declaredArtifacts:n,changes:N,unattributed:y,unresolvedScopes:U,noCodeReason:a,...vt?{gitAdvisory:vt}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,m=l.length,g=r.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let x=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:b});if(Ra({...x,scopeHash:b})<=oi)break;if(g){g=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let w=o.totalChanges>h||d>m?D_({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):b,E=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:w}),k={...E,scopeHash:j(Ow,E)};if(Ra(k)>oi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return k}function Gd(e){let t=qd(e.baseline),r=qd(e.current),i=Vw(e);return{authority:i,baseline:t,current:r,scope:qw(t,r,i)}}function At(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _t(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function ai(e,t){if(typeof e!="string"||!Wd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _w(e,t,r){let i=Fd(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function Qs(e,t){let r=At(e,"Native snapshot projection");if(_t(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==$w)throw new Error("Native snapshot projection schema is invalid");let i=Xr({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=qd(i);if(j(xa,r)!==j(xa,n))throw new Error("Native snapshot projection is not canonical");let a=j(xa,n);if(t!==void 0&&ai(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Ud(e,t){let r=At(e,`Declared artifact ${t}`);if(_t(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:_r(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Iw(e,t){if(e===null)return null;let r=At(e,t);return _t(r,["hash","size"],[],t),{hash:ai(r.hash,`${t} hash`),size:tn(r.size,`${t} size`)}}function Tw(e,t){let r=At(e,`Implementation change ${t}`);if(_t(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Ud),n=Aa(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Iw(r.before,`Implementation change ${t} before`),o=Iw(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:_r(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function L_(e,t){let r=At(e,`Unresolved scope ${t}`);_t(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?Hw(r.path,`Unresolved scope ${t} path`):_r(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Pa(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>_r(n,`${t} ${a}`)),i=[...new Set(r)].sort(be);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function Mw(e){let t=At(e,"Native implementation external drift");if(_t(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Pa(t.paths,"Native external drift paths");return Lw({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Zs(e){let t=At(e,"Native implementation scope"),r=[...B_].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(_t(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Vd)throw new Error("Native implementation scope schema is invalid");let i=ai(t.contractHash,"Implementation scope contractHash"),n=ai(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_w(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=ai(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_w(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Ud);if(JSON.stringify(c)!==JSON.stringify(Aa(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Tw),u=[...l].sort((y,C)=>be(y.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(C=>!d.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(C=>_a(C,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Tw),p=t.externalDrift===void 0?void 0:Mw(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(y=>y.attributedTo.length===0&&!v.has(y.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(L_),g=m.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let b=g[0]===void 0?null:H_(g[0]);if(b&&(b.changes+b.unresolved===0||b.unattributed>b.changes||b.unattributed>b.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,w=[...h.map(y=>Jt({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(b?.changes??0)===0&&S===null?[Jt({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=m.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Md))||new Set(m.map(y=>y.id)).size!==m.length||JSON.stringify(E)!==JSON.stringify(w.sort(Md))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let k;if(t.gitAdvisory!==void 0){let y=At(t.gitAdvisory,"Implementation scope Git advisory");if(_t(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Pa(y.changedPaths,"Git changed paths"),O=Pa(y.pathsPresentInSnapshotChanges,"Git present paths"),$=Pa(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),de=[...O,...$].sort(be);if(JSON.stringify(de)!==JSON.stringify(C)||$.some(ee=>l.some(U=>U.path===ee)))throw new Error("Implementation scope Git advisory partition is invalid");k={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:O,pathsAbsentFromSnapshotChanges:$}}let x={schema:Vd,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...k?{gitAdvisory:k}:{},...p?{externalDrift:p}:{}},N=ai(t.scopeHash,"Implementation scope scopeHash");if(j(Ow,x)!==N)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:N}}function V_(e){let t=At(e,"Native implementation scope authority");if(_t(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Ud);if(JSON.stringify(r)!==JSON.stringify(Aa(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=Pa(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Mw(t.externalDrift),a=Vw({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Ia(e){let t=At(e,"Native implementation scope bundle");_t(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=V_(t.authority),i=Qs(t.baseline),n=Qs(t.current),a=Zs(t.scope),o=qw(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function Ww(e){let t=Zs(e.scope);return Ia({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var Vd,$w,xa,Ow,b_,k_,S_,Wd,oi,E_,C_,B_,si=A(()=>{"use strict";pe();Ji();Vd="comet.native.implementation-scope.v2",$w="comet.native.content-snapshot-projection.v1",xa="comet.native.content-snapshot-projection.v1",Ow="comet.native.implementation-scope.v2",b_="comet.native.unresolved-scope-id.v1",k_="comet.native.scope-detail-overflow.v1",S_="comet.native.snapshot-projection-overflow.v2",Wd=/^[a-f0-9]{64}$/u,oi=1024*1024,E_=128,C_=128;B_=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import zw from"node:path";function Gt(e,t){if(!Gw.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Uw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Kw(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Kd(e,t,r=2e3){let i=Ke(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Ta(e,t){let r=zw.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||zw.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function W_(e,t,r){let i=Ta(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Nt(i),a=i.toLowerCase(),o=r?Ta(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Yd(e){let t=Ta(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function rn(e,t){return e<t?-1:e>t?1:0}function ec(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tc(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Yw(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Jw(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function z_(e){let t=ec(e,"Native acceptance trace");if(tc(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Gw.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=Ta(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=ec(o,`Native acceptance trace entry ${s}`);if(tc(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Yd(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(rn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Ta(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Kd(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>rn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=Gt(t.traceHash,"Native acceptance trace hash");if(j(F_,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Xw(e){let t=ec(e,"Native partial allowance");if(tc(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(rn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:Kw(t.change),scopeHash:Gt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Kd(t.reason,"Partial allowance reason"),confirmedSummary:Kd(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Uw(t.sourceRevision),confirmedAt:Yw(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=Gt(t.allowanceHash,"Native partial allowance hash");if(j(q_,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Xd(e){let t=ec(e,"Native verification evidence");if(tc(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=Gt(t.implementationScopeHash,"Native verification implementation scope hash"),i=z_(t.acceptanceTrace),n=Gt(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Gt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Yd(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(rn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(rn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Yd(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(rn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Kw(t.change),sourceRevision:Uw(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Gt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Jw(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:W_(t.reportRef,"Native verification report ref"),reportHash:Gt(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:Jw(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Yw(t.createdAt,"Native verification timestamp")},d=Gt(t.envelopeHash,"Native verification envelope hash");if(j(M_,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var Gw,F_,q_,M_,rc=A(()=>{"use strict";pe();ti();Gn();si();Gw=/^[a-f0-9]{64}$/u,F_="comet.native.acceptance-trace.v2",q_="comet.native.partial-allowance.v1",M_="comet.native.verification-evidence.v2"});import Qw from"node:path";function Ir(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tr(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function Ut(e,t){if(typeof e!="string"||!G_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Be(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ny(e,t){let r=Be(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function ry(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function eI(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>X_||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=Qw.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Qw.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function tI(e){let t=Ir(e,"Native check receipt checker");Tr(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Ir(t.limits,"Native check receipt limits");if(Tr(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==nn||t.version!==Qd||t.hash!==ey||r.maxFiles!==Te.maxFiles||r.maxFileBytes!==Te.maxFileBytes||r.maxTotalBytes!==Te.maxTotalBytes||r.maxIssues!==Te.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:nn,version:Qd,hash:ey,limits:{...Te}}}function rI(e){let t=Ir(e,"Native check receipt contract");return Tr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Ut(t.expectedHash,"Native check expected contract hash"),beforeHash:Ut(t.beforeHash,"Native check before contract hash"),afterHash:Ut(t.afterHash,"Native check after contract hash")}}function iI(e){let t=Ir(e,"Native check receipt implementation");return Tr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Ut(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Ut(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Ut(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Ut(t.afterSnapshotHash,"Native check after snapshot hash")}}function nI(e,t){let r=Ir(e,`Native check batch ${t}`);Tr(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Be(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Be(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Be(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Be(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Be(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Be(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Te.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Te.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function aI(e){let t=Ir(e,"Native check receipt counts");Tr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Be(t.filesSelected,"Native check filesSelected"),filesScanned:Be(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Be(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Be(t.bytesScanned,"Native check bytesScanned"),issueCount:Be(t.issueCount,"Native check issueCount"),recordedIssueCount:Be(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(nI):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Te.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Te.maxFiles||r.bytesScanned>Te.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function oI(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||ty.indexOf(e.kind)-ty.indexOf(t.kind)}function sI(e){if(!Array.isArray(e)||e.length>Te.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Ir(i,`Native check issue ${n}`);if(Tr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!Q_.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:eI(a.path,`Native check issue ${n} path`),line:ny(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(oI);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function cI(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!Z_.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=iy.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function lI(e){return j(Y_,e)}function ay(e){let t=Ir(e,"Native check receipt");if(Tr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Zw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!U_.test(t.change))throw new Error("Native check receipt change name is invalid");let r=ny(t.sourceRevision,"Native check source revision"),i=tI(t.checker),n=rI(t.contract),a=iI(t.implementation),o=lI({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Ut(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=ry(t.startedAt,"Native check receipt startedAt"),c=ry(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=aI(t.counts),u=sI(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=cI(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Te.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Te.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:Zw,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Ut(t.receiptHash,"Native check receipt content hash");if(j(J_,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}var Zw,J_,nn,Qd,Te,G_,U_,K_,Y_,X_,ey,Q_,ty,iy,Z_,Zd=A(()=>{"use strict";pe();Zw="comet.native.check-receipt.v1",J_="comet.native.check-receipt.v1",nn="scoped-text-safety",Qd=1,Te=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),G_=/^[a-f0-9]{64}$/u,U_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,K_="comet.native.checker-policy.v1",Y_="comet.native.check-input.v1",X_=2048,ey=j(K_,{policy:nn,version:Qd,limits:Te,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Q_=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),ty=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],iy=["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"],Z_=new Set(iy)});function an(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function jr(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Kt(e,t){if(typeof e!="string"||!fI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ht(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Ke(e).trim();if(!r||r.length>vI||r!==e.trim())throw new Error(`${t} is invalid`);return r}function ef(e,t){let r=ht(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function ja(e,t,r=ht,i=!1,n=gI){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function yI(e,t){if(typeof e!="string"||!pI.test(e))throw new Error(`${t} is invalid`);return e}function NI(e){let t=an(e,"Native verification receipt bindings");if(jr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!hI.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Kt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Kt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Kt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Kt(t.artifactHash,"Native verification receipt artifact hash")}}function bI(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=mI.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function kI(e,t,r,i){let n=an(t,`Native ${e} evidence`);if(e==="automated-check"){if(jr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=ef(n.startedAt,"Native automated-check start time"),o=ef(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=an(n.worktree,"Native automated-check worktree");if(jr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=an(n.afterFence,"Native automated-check after fence");if(jr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ht(n.executable,"Native automated-check executable"),args:ja(n.args,"Native automated-check arguments",ht,!0),cwd:ht(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ht(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Kt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Kt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Kt(n.outputHash,"Native automated-check output hash"),outputSummary:ht(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){jr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=bI(n.checkReceiptRef);if(Kt(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:ja(n.subjects,"Native static inspection subjects",ht,i==="required-check"),rule:ht(n.rule,"Native static inspection rule"),resultSummary:ht(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:ja(n.steps,"Native manual evidence steps"),observations:ja(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function SI(e){let t=an(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=ht(t.actor,"Native verification receipt actor"),o=ja(t.acceptanceIds,"Native receipt acceptance IDs",yI,i==="required-check",wI).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:tf,kind:r,role:i,status:n,bindings:NI(t.bindings),acceptanceIds:o,actor:a,issuedAt:ef(t.issuedAt,"Native verification receipt issue time"),evidence:kI(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==nn||s.actor!==`native-runtime:${nn}`))throw new Error("Native required check policy identity is invalid");return s}function oy(e){let t=an(e,"Native verification receipt");if(jr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==tf)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=SI(i),a=Kt(t.receiptHash,"Native verification receipt hash");if(j(uI,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function rf(e){return j(dI,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var tf,uI,dI,fI,pI,hI,mI,vI,gI,wI,$a=A(()=>{"use strict";pe();Zd();ti();tf="comet.native.verification-receipt.v3",uI=tf,dI="comet.native.declared-artifacts.v1",fI=/^[a-f0-9]{64}$/u,pI=/^acceptance-[a-f0-9]{64}$/u,hI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,mI=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,vI=4096,gI=256,wI=1024});import{createHash as EI}from"node:crypto";import{promises as mt}from"node:fs";import It from"node:path";function nf(e,t){let r=It.relative(e,t);return r===""||!It.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${It.sep}`)}function CI(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ic(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function sy(e){let t=await mt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await mt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function xI(e,t){let r=It.resolve(e),i=It.resolve(t);if(!nf(r,i))throw new Error("Native evidence path is outside its change");let n=[await sy(r)],a=r;for(let o of It.relative(r,i).split(It.sep).filter(Boolean)){a=It.join(a,o);let s=await sy(a);if(!nf(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function cy(e){for(let t of e){let r=await mt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!CI(t,r)||await mt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function PI(e,t,r={}){let i=await xI(t,It.dirname(e));await r.afterParentChainCaptured?.();let n=await mt.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await mt.realpath(e);if(!nf(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await mt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),mt.lstat(e),mt.realpath(e)]);if(await cy(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ic(s,n)||!ic(s,c))throw new Error("Native evidence document changed while opening");if(s.size>on)throw new Error(`Native evidence document exceeds ${on} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=on+1-d,g=await o.read(f,0,Math.min(f.length,m),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>on)throw new Error(`Native evidence document exceeds ${on} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),mt.lstat(e),mt.realpath(e)]);if(await cy(i),!v.isFile()||v.isSymbolicLink()||h!==a||!ic(s,p)||!ic(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function dy(e,t){if(!uy.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function RI(e,t,r,i,n){if(!uy.test(r))throw new Error("Native report evidence hash is invalid");let a=await ci({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||EI("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function sn(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function AI(e,t,r,i,n){let a=dy(r,i);return n?It.join(n,...a.split("/")):wr(K(e,t),a)}async function ci(e){let t=AI(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??me(e.paths,t);return await G(r,t),PI(t,r,e.hooks)}function ly(e,t){return Qs(e,t)}function _I(e,t){let r=Zs(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function II(e,t,r){let i=Xw(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function TI(e,t,r){let i=Xd(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function jI(e,t,r,i=!1,n){let a=await nc(e,t,r.implementationScopeRef,void 0,n);if(i&&await RI(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await fy(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function Oa(e,t,r,i,n){let a=sn(r,"scopes"),o=_I(await ci({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=sn(o.baselineProjectionRef,"snapshots"),c=sn(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ci({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ly(d,s)),ci({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ly(d,c))]);return Ww({baseline:l,current:u,scope:o})}async function nc(e,t,r,i,n){return(await Oa(e,t,r,i,n)).scope}async function fy(e,t,r,i,n){let a=sn(r,"allowances");return II(await ci({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Ha(e,t,r,i,n){let a=sn(r,"receipts"),o=oy(await ci({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function cn(e,t,r,i,n){let a=sn(r,"verifications"),o=TI(await ci({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await jI(e,t,o,!1,n),o}var uy,on,NF,$r=A(()=>{"use strict";se();Y();bt();si();rc();$a();uy=/^[a-f0-9]{64}$/u,on=oi,NF=3*on});gt();pe();ge();We();import Qt from"node:path";import{realpathSync as u$}from"node:fs";import{promises as qj}from"fs";Gr();ge();nt();xt();Y();import{promises as gd}from"fs";import Mg from"path";var Wg=["outcome","scope","nonGoals","acceptanceExamples"],SA=[...Wg,"constraints","decisions","openQuestions","verificationExpectations"],EA=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],zg={maxFileBytes:Kn};function Jg(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
170
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function CA(e,t){let r=Mg.resolve(e,...t.split(/[\\/]/u));if(!F(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await gd.realpath(e),n=await gd.realpath(r);if(!F(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await gd.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Na(e){return{valid:e.length===0,findings:e}}function Gg(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function wd(e,t){let r=[],i;try{i=(await ae({root:e,ref:t,maxBytes:zg.maxFileBytes})).text}catch(a){return Na([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jg(i))n.set(Uo(a)??a,o);for(let a of SA)n.has(a)||r.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of Wg)(n.get(a)??"").length===0&&r.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return Gg(i)&&r.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Na(r)}async function yd(e,t){let r=[],i;try{i=(await ae({root:e,ref:t,maxBytes:zg.maxFileBytes})).text}catch(a){return Na([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jg(i))n.set(Um(a)??a,o);for(let a of EA)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Na(r)}function Vs(e,t){return Mg.join(e.specsDir,t,"spec.md")}async function Ug(e,t){let r=[],i=ye(e,t.name);for(let n of t.spec_changes){let a=Vs(e,n.capability),o=null;try{await G(e.nativeRoot,a),o=await Uu(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await CA(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Na(r)}na();pe();ge();nt();na();pe();import Kg from"node:path";var xA="comet.native.contract.v1",PA="comet.native.acceptance-set.v1",Yg=/^[a-f0-9]{64}$/u,ba={maxAcceptanceCriteria:ia.maxCriteria};function Xg(e,t){let r=Kg.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||Kg.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Qg(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
171
+ `))}function RA(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Yg))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Yg))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Xg(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Qg(e.markdown)},markdown:e.markdown}}function AA(e,t){return Zg(e.id,t.id)}function Zg(e,t){return e<t?-1:e>t?1:0}function ew(e){let t=Xg(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(RA).sort((d,f)=>Zg(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=$u(e.briefMarkdown,t,ba.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Ou(f,d.source,ba.maxAcceptanceCriteria-a.length)),a.push(...wv(f,d.source,ba.maxAcceptanceCriteria-a.length)));if(a.sort(AA),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>ba.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${ba.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Qg(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(PA,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(xA,u)}}var Fs={maxSpecs:64,maxFileBytes:Kn,maxTotalBytes:4*1024*1024};async function Xi(e){if(e.specChanges.length>Fs.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ae({root:e.changeDir,ref:e.briefRef,maxBytes:Fs.maxFileBytes}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await ae({root:e.changeDir,ref:n.source,maxBytes:Fs.maxFileBytes});if(r+=a.size,r>Fs.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:ew({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}Zn();import _A from"path";var Nd="comet.selection.v2",IA=16*1024;function rw(e){return _A.join(e,".comet","current-change.json")}function TA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tw(e){return e===null||typeof e=="string"}function jA(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(!TA(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&&!tw(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Nd,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Nd)throw new Error(`current change selection schema must be ${Nd}`);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(!tw(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 iw(e){let t;try{let i=rw(e),{bytes:n}=await Pi(i,IA,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...jA(t)}}ge();We();lt();gt();se();import{promises as OI}from"node:fs";import af from"node:path";nt();pe();Ea();Sa();ge();Ed();yr();ds();ka();Ms();se();aa();import{promises as h_}from"node:fs";import Sw from"node:path";function Us(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ks(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 Rt(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 Ew(e,t){return e===null?null:Rt(e,t)}function Xs(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 m_(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 v_(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Ys(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Bd(e,t){if(e===null)return null;let r=Rt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Ld(e,t){let r=Rt(e,t);if(!Sw.isAbsolute(r))throw new Error(`${t} must be absolute`);return Sw.resolve(r)}function g_(e,t){let r=`Native local checks[${t}]`,i=Us(e,r);if(Ks(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)=>Rt(l,`${r}.argv[${u}]`,!0)),a=Ys(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Bd(i.startedAt,`${r}.startedAt`),s=Bd(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=Xs(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Rt(i.id,`${r}.id`),name:Rt(i.name,`${r}.name`),operationId:Rt(i.operationId,`${r}.operationId`),status:a,repeatable:v_(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Xs(i.executionCount,`${r}.executionCount`),argv:n,cwd:Ld(i.cwd,`${r}.cwd`),exitCode:m_(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Rt(i.log,`${r}.log`)}}function w_(e){let t="Native local execution state",r=Us(e,t);if(Ks(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ss)throw new Error(`Native local execution schema must be ${ss}`);let i=Us(r.workspace,"Native local workspace");Ks(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Us(r.execution,"Native local execution");Ks(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Bd(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Rt(o.operationId,"Native local execution.operationId"),stage:Ys(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Ys(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ew(o.executionId,"Native local execution.executionId"),status:Ys(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Xs(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(g_);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:ss,change:Rt(r.change,"Native local change"),basedOnStateVersion:Xs(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ld(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ld(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ew(i.branch,"Native local workspace.branch")},execution:n,checks:a}}async function Cw(e){let t;try{t=await h_.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return w_(r)}lt();Hu();yr();Wu();ds();ka();Ms();se();Gr();ka();Y();Gr();$r();We();var HI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DI="comet-state.yaml",BI="state.json",Cq=Ko("en");function py(e,t){if(!HI.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=af.join(e.changesDir,t);if(!F(e.changesDir,r))throw new Error("Native change path escaped");return r}function hy(e,t){return af.join(py(e,t),DI)}function LI(e,t){return af.join(gr(e,t),BI)}async function of(e,t){try{let r=await OI.readFile(hy(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}async function my(e,t){return Bt(hy(e,t))}async function vy(e){let t=await my(e.paths,e.name),r=LI(e.paths,e.name);try{let i=await Cw(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var Oq=16*1024;async function gy(e){let t=await iw(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Bs(t.selection.change),t.selection)}Gi();Y();Zr();Is();async function wy(e,t){let r=[],i=K(e,t.name),n=wr(i,Ue.stateRef),a;try{a=await Ki(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=wr(i,a.trajectoryRef),s=await kg(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Qr(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=wr(i,a.checkpointRef);try{let u=await _s(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Ji();Gi();se();ge();xt();ra();lt();Y();ct();ti();import oT from"path";import{isDeepStrictEqual as hf}from"util";pe();pe();var ln={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var VI=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function FI(e,t){return e<t?-1:e>t?1:0}function qI(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!VI.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(FI)}function sf(e=[]){return qI(e,"Native repair failed check IDs",ln.maxFailedCheckIds,!0)}function yy(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function MI(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:yy(e.failedAcceptanceIds,t.failedAcceptanceIds)&&yy(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function cf(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(MI(i,a))break;r+=1,i=a}return r}rc();si();function lf(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var Ny="repairStagnation",Le={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},zI=/^[a-f0-9]{64}$/u;var JI=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),GI=["data","runId","sequence","timestamp","type"],by=["disposition","overrideSummaryHash","signatureHash"],UI=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],ky=12;function df(e,t){return e<t?-1:e>t?1:0}function Sy(e,t,r){let i=Object.keys(e).sort(df);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Da(e,t){if(typeof e!="string"||!zI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function KI(e){if(!Array.isArray(e)||e.length>ln.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(df)}function Ey(e){if(typeof e!="string"||e.length===0||e.length>Le.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function uf(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Le.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Le.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Le.maxTextCharacters&&(!n||e.length>Le.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Le.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Le.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>uf(s,t+1,r,`${i}[${c}]`));return}let a=ac(e,i),o=Object.keys(a);if(o.length>Le.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Le.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Le.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");uf(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function YI(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function XI(e,t,r){let i=ac(e,`Native repair trajectory event ${t+1}`);if(Sy(i,GI,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(YI(i.timestamp),typeof i.type!="string"||!JI.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(Ey(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return uf(i.data,0,n,"Native trajectory event data"),ac(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function ff(e){let t=ac(e,"Native repair trajectory projection"),r=Object.keys(t).sort(df),i=r.length===by.length&&r.every((l,u)=>l===by[u]);i||Sy(t,UI,"Native repair trajectory projection");let n=Da(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Da(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Da(t.contractHash,"Native repair trajectory contract hash"),s=KI(t.failedAcceptanceIds),c=sf(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function QI(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function ZI(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??ky;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=cf({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<ln.warningAtConsecutiveFailures?"continue":a<ln.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function eT(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??ky;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function Cy(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Le.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Ey(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=XI(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Le.maxTotalDataNodes||c>Le.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Da(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Da(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,Ny)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=ff(f[Ny]);if(QI(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(r.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),ZI(v,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");eT(v,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(i=v,r.length>ln.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function xy(e){return Cy(e).history}function Py(e){let t=Cy(e).latestProjection;return t?{...t}:null}xt();var un={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:[]},pf=X("comet-native-runtime:v3:scope-reopen"),tT=[{skillVersion:"3",skillHash:X("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:X("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:X("comet-native-runtime:v1")}];function Ry(e){return e.skillVersion===un.definition.metadata.version&&e.skillHash===pf||tT.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}Zr();xt();Zr();xt();function Ay(e){return X(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}Is();fs();var $y=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],sT=new Set($y),Oy=new Set([...$y,"minimum_runtime_version","revision"]),cT=new Set([...Oy,"operation"]),lT=512*1024,mf=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),uT=new Set([...mf,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),vf=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function wf(e,t){return oT.join(K(e,t),"transition.json")}function sc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function yf(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function oc(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!uT.has(u)),a=[...mf].find(u=>!Object.hasOwn(r,u)),o=mf.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(lf(r.summary,"Native transition journal event summary"),Ke(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(r.noCodeReason!==null&&(lf(r.noCodeReason,"Native transition journal event no-code reason"),Ke(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?ff(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function dT(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return gf({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return gf(e,t)}function Nf(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?dT(e.eventData,e.evidenceHash):gf(e.eventData,e.evidenceHash),n=sd(e.nextRun),a=e.previousRun===null?null:sd(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function _y(e,t,r=!1){if(e.skill!==un.definition.metadata.name||(r?!Ry(e):e.skillVersion!==un.definition.metadata.version||e.skillHash!==pf)||e.orchestration!==un.definition.orchestration.mode||e.pendingRef!==Ue.pendingRef||e.trajectoryRef!==Ue.trajectoryRef||e.contextRef!==Ue.contextRef||e.artifactsRef!==Ue.artifactsRef||e.checkpointRef!==Ue.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Iy(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ty(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function bf(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(_y(o,"next Run",i||a!==null),Ty(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(_y(a,"previous Run",!0),Ty(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!hf(Iy(a),Iy(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function fT(e,t,r){return X(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function Hy(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function jy(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function kf(e,t,r,i,n=!1){let a=r.eventData,o=jy(e),s=jy(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&hf(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&hf(e.spec_changes,t.spec_changes),l=Ay({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(i==="spec-rebase"){let c=fT(e.name,a.summary,t.spec_changes),l=X(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function pT(e,t){let r=sc(e);if(yf(r,cT),r.schema!==Di)throw new Error(`Expected Native transition schema ${Di}`);let i=oc(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Di} minimum_runtime_version must be ${3}`);let n=oc(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Nf(r,t),o=Sr(r.previousState),s=Sr(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(kf(o,s,a,r.operation),bf(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Di,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function hT(e,t){let r=sc(e);if(yf(r,sT),r.schema!==sa)throw new Error(`Expected Native transition schema ${sa}`);let i=Nf(r,t,!0),n=Li(r.previousState),a=Li(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return kf(n,a,i,Hy(n,a,i.eventData),!0),bf(n,a,i,!0),{schema:sa,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function mT(e,t){let r=sc(e);if(yf(r,Oy),r.schema!==Bi)throw new Error(`Expected Native transition schema ${Bi}`);if(oc(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Bi} minimum_runtime_version must be 2`);let n=oc(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Nf(r,t,!0),o=Vi(r.previousState),s=Vi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(kf(o,s,a,Hy(o,s,a.eventData),!0),bf(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Bi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function vT(e,t){let r=sc(e);if(r.schema===Di)return{status:"current",journal:pT(r,t)};if(r.schema===sa)return{status:"migration-required",journal:hT(r,t)};if(r.schema===Bi)return{status:"migration-required",journal:mT(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function gT(e,t){let r=wf(e,t),i=me(e,r);await G(i,r);try{let n=await Lt({root:i,file:r,maxBytes:lT,label:`Native transition journal ${t}`});return vT(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Dy(e,t){let r=await gT(e,t);if(!r)return null;if(r.status==="migration-required")throw new vf(t);return r.journal}xr();var wT=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function yT(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function NT(e){return e?e.map(yT).join(" "):null}function bT(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function Ye(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function kT(e){return e.map(t=>Ye(t,[],null))}function ST(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[Ye("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(Ye("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(Ye("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Ye("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(Ye("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(Ye("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Ye("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function ke(e,t){let r=t.commandArgs===void 0?bT(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?NT(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??kT(t.requiredInputs??[])}}function cc(e){let r=(e.findings??[]).filter(d=>!Yi(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||wT.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Ye("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Ye("summary",["--summary"],"<summary>")]});if(n)return ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Ye("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Ye("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=ST(e.state);return ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}ge();Y();xr();import Ba from"path";var By=8,ET={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function CT(e){let t=ET[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Yi(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function xT(e,t,r){if(!r.path)return null;let i;if(Ba.isAbsolute(r.path)?i=Ba.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Ba.resolve(ye(e,t.name),...r.path.split(/[\\/]/u)):i=Ba.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!F(e.projectRoot,i))return null;let n=Ba.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function PT(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function Sf(e){return e.findings.map(t=>{let r=CT(t.code);return{code:t.code,message:t.message,severity:r.severity,path:xT(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:PT(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function Ef(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,By),truncated:t.length>By}}se();ge();xt();Y();ct();Gn();ti();import dn from"path";var Hr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},fn=/^[a-f0-9]{64}$/u;function lc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function uc(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Or(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function Ly(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Cf(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function RT(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||dn.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=dn.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Vy(e,t){return dn.join(K(e,t),"checkpoints","progress.json")}function La(e,t){return dn.join(K(e,t),"checkpoint-journal.json")}function Fy(e,t,r){if(!fn.test(r))throw new Error("Native checkpoint manifest hash is invalid");return dn.join(K(e,t),"checkpoints","manifests",`${r}.json`)}function AT(e){if(!fn.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function xf(e,t,r){let i=await Lt({root:e,file:t,maxBytes:Hr.maxDocumentBytes,label:r});return JSON.parse(i.bytes.toString("utf8"))}function _T(e,t){let r=lc(e,`checkpoint manifest artifact ${t}`);uc(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=RT(Or(r.path,`checkpoint artifact ${t} path`,4096)),n=Nt(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!fn.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Cf(r.size,`checkpoint artifact ${t} size`)}}function Pf(e,t){let r=lc(e,"Native checkpoint manifest");if(uc(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Hr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(_T),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Cf(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Hr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function qy(e){return X(JSON.stringify(Pf(e,e.change)))}function My(e,t){let r=lc(e,"Native progress checkpoint");if(uc(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Ly(r.previousRevision,"Native checkpoint previousRevision"),a=Ly(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Or(r.manifestHash,"Native checkpoint manifestHash",64);if(!fn.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=AT(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Or(r.inputHash,"Native checkpoint inputHash",64);if(!fn.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Or(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Cf(r.artifactCount,"Native checkpoint artifactCount");if(u>Hr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Or(r.summary,"Native checkpoint summary"),f=Or(r.nextAction,"Native checkpoint nextAction");if(Ke(d)!==d||Ke(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Or(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function IT(e,t){let r=lc(e,"Native checkpoint journal");if(uc(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=Sr(r.previousState),n=Sr(r.nextState),a=My(r.checkpoint,t),o=Pf(r.manifest,t),s=Or(r.inputHash,"Native checkpoint journal inputHash",64),c=X(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!fn.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==qy(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function TT(e,t,r){let i=dn.resolve(e.projectRoot,...t.split("/"));if(!F(e.projectRoot,i)||F(e.nativeRoot,i)||F(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=cu(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Lt({root:e.projectRoot,file:i,maxBytes:Hr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function jT(e,t){let r=Vy(e,t),i=me(e,r);await G(i,r);try{return My(await xf(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function $T(e,t,r){let i=Fy(e,t,r),n=me(e,i);await G(n,i);let a=await xf(n,i,"Native checkpoint manifest"),o=Pf(a,t);if(Wy(e,o),qy(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Rf(e,t){let r=La(e,t),i=me(e,r);await G(i,r);try{let n=IT(await xf(i,r,"Native checkpoint journal"),t);return Wy(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}function Wy(e,t){for(let r of t.artifacts){let i=cu(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function zy(e){let t;try{t=await jT(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Vy(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await $T(e.paths,e.name,t.manifestHash);let a=X(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await TT(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fy(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}var Jy=240,Gy=8,dc=50;function Uy(e){let t=Array.from(e);return t.length<=Jy?e:`${t.slice(0,Jy-1).join("")}…`}function OT(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function HT(e){let t=[...new Set(e.map(OT))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Gy),reasonCount:e.length,codesTruncated:t.length>Gy};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,dc),reasonsTruncated:e.length>dc}}}async function Ky(e){let t=null;try{let s=await Rf(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:La(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:La(e.paths,e.state.name)}}let r=await zy({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=HT(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Hr.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:Uy(r.checkpoint.summary),nextAction:Uy(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Hr.maxArtifacts}}import{promises as Oj}from"node:fs";import hN from"node:path";pe();import Yy from"node:path";var DT="comet.native.archive-preflight.v1",BT="comet.native.archive-preflight.v1",LT="comet.native.archive-operation.v1",VT=/^[a-f0-9]{64}$/u,Xy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function fc(e,t){return e<t?-1:e>t?1:0}function qT(e,t){if(typeof e!="string"||!VT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Yt(e,t){return e===null?null:qT(e,t)}function MT(e,t){let r=Yy.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Yy.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function WT(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function zT(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function JT(e,t){if(!Xy.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=Yt(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=Yt(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Yt(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function GT(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Yt(e.contractHash,"Native archive contract hash"),acceptanceHash:Yt(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Yt(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Yt(e.reportHash,"Native archive report hash"),envelopeHash:Yt(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Yt(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function UT(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!FT.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(fc);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function KT(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(fc)}function Qy(e){if(!Xy.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(JT).sort((l,u)=>fc(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:j(LT,l)})),i=GT(e.evidence),n=zT(e.workspace),a=[...new Set([...UT(e.findingCodes??[]),...KT({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(fc),o=WT(e.revision),s=MT(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:DT,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:j(BT,c)}}nt();ge();pe();import{createHash as YT}from"node:crypto";import Zy from"node:path";var XT="comet.native.conflict-radar.v1",je=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}),QT="comet.native.conflict-radar.v1",ZT="comet.native.conflict-radar-signals.v1",ej=/^[a-f0-9]{64}$/u,rN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tj=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),rj=new Set(["capability","operation","baseHash"]),ij=new Set(["path","kind"]);function pn(e,t){return e<t?-1:e>t?1:0}function Af(e){return Buffer.byteLength(e,"utf8")}function _f(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function If(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Af(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function nj(e,t){let r=If(e,t,je.maxArtifactPathBytes),i=Zy.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Zy.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function iN(e,t){if(typeof e!="string"||!ej.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function aj(e,t){let r=_f(e,rj,t),i=If(r.capability,`${t} capability`,je.maxCapabilityBytes);if(!rN.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:iN(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function oj(e,t){let r=_f(e,ij,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:nj(r.path,`${t} path`),kind:r.kind}}function sj(e,t){let r=_f(e,tj,`Conflict radar change ${t}`),i=If(r.name,`Conflict radar change ${t} name`,je.maxNameBytes);if(!rN.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>je.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>je.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>aj(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>pn(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>oj(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>pn(c.path,l.path)||pn(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:iN(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function cj(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>je.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(sj).sort((n,a)=>pn(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>je.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>je.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function lj(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function uj(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function dj(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function fj(e,t){let r=[],i=YT("sha256").update(`${ZT}
172
+ [`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(vn(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<je.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(lj(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=uj(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:dj(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function eN(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function pj(e,t){return eN(e.classification)-eN(t.classification)||pn(e.left,t.left)||pn(e.right,t.right)}function tN(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:XT,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function nN(e){let t=cj(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(fj(t[s],t[c]));r.sort(pj);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(QT,{changes:t,relationships:i}),a=r.slice(0,je.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=tN(t,r,a,n);for(;a.length>0&&Af(JSON.stringify(o))>je.maxSerializedBytes;)a=a.slice(0,-1),o=tN(t,r,a,n);if(Af(JSON.stringify(o))>je.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}$r();ct();xr();var hj=4096;async function mj(e,t=je.maxChanges){try{let r=await ca({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function aN(e,t){let r=await Wt(e,t),[i,n]=await Promise.all([r.implementation_scope?nc(e,t,r.implementation_scope):null,qt(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function pc(e,t,r={}){let n=(await mj(e,hj)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await aN(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await aN(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=nN([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}ge();We();Y();na();nt();ge();$r();Ji();si();rc();import{execFile as xj}from"node:child_process";qs();Sd();ge();import{promisify as Pj}from"node:util";ge();lt();se();Zd();Y();bt();import{constants as Tf,promises as Xe}from"node:fs";import hn from"node:path";var gj=/^[a-f0-9]{64}$/u,wj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Va=512*1024;function yj(e,t){return W({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Fe(r,i)?W(r,i):W(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Nj(e,t){let r=hn.resolve(e),i=hn.resolve(t);if(!F(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...hn.relative(r,i).split(hn.sep).filter(Boolean)]){o&&(a=hn.join(a,o));let s=await Xe.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Xe.realpath(a);if(n.length>0&&!F(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function sN(e){for(let t of e){let r=await Xe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!yj(t,r)||await Xe.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function bj(e){if(!gj.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function kj(e){let t=wj.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function Sj(e,t,r){return wr(K(e,t),bj(r))}async function Ej(e,t,r){let i=await Nj(r,hn.dirname(e)),n=await Xe.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Va)throw new Error(`Native check receipt exceeds ${Va} bytes`);let[a,o]=await Promise.all([Xe.realpath(t),Xe.realpath(e)]);if(!F(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Tf.O_RDONLY|Tf.O_NOFOLLOW|Tf.O_NONBLOCK,c=await Xe.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Xe.lstat(e),Xe.realpath(e)]);if(await sN(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!hc(n,l)||!hc(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let b=Va+1-p,S=await c.read(v,0,Math.min(v.length,b),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>Va)throw new Error(`Native check receipt exceeds ${Va} bytes`);f.push(Buffer.from(v.subarray(0,S.bytesRead)))}let[h,m,g]=await Promise.all([c.stat(),Xe.lstat(e),Xe.realpath(e)]);if(await sN(i),!m.isFile()||m.isSymbolicLink()||g!==o||!F(a,g)||!hc(l,h)||!hc(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function cN(e,t,r){let i=kj(r),n=K(e,t),a=Sj(e,t,i),o=me(e,a);await G(o,a);let s=ay(await Ej(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}$r();lt();ti();var Fa=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Ji();$a();si();var JW=64*1024;var GW=3600*1e3;var UW=Pj(xj);var Rj=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function lN(e,t){let r=[];for(let i of Rj){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function uN(e){if(e.receipt.kind!=="static-inspection")return null;let t=await cN(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}$a();var Dr=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}};function Aj(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function _j(e){let t=Aj(e.bundle.baseline),r=await nd(e.paths,t,{origin:"explicit",now:e.now});return Gd({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function fN(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Oa(e.paths,e.state.name,e.state.implementation_scope),r=await Xi({changeDir:ye(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await _j({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function pN(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await fN(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function Ij(e){let t=await ae({root:ye(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Nv(t.text)}}function Tj(e){let{receipt:t,implementationScope:r}=e,i=[],n=Jd({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function jj(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:rf(e.implementationScope.scope.declaredArtifacts)}}async function dN(e){let t=await Ha(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=lN(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new Dr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await uN({paths:e.paths,state:e.state,receipt:t});if(n){let a=Tj({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function $j(e){let t=jj({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await dN({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Dr)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await dN({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Dr)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new Dr(r)}function jf(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function $f(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:jf(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([fN(e),cn(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:jf(e.state.verification_result,"stale"),envelope:null};let i=await Ij({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await $j({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:jf(e.state.verification_result,"invalid"),envelope:null}}}xr();function Hj(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function mN(e){try{return await Oj.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dj(e,t){try{return(await ae({root:e,ref:t})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Bj(e,t,r){let i=Vs(e,r.capability);if(!F(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=hN.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await Dj(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await ae({root:ye(e,t),ref:r.source})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function Lj(e,t){return mN(wf(e,t))}async function Of(e){let t=e.now??new Date,r=await Wt(e.paths,e.name),i=await qt(e.paths,e.name),n=await Ae(e.paths.projectRoot),a=Hj(r.name,t),o=hN.resolve(e.paths.nativeRoot,...a.split("/"));if(!F(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(r.spec_changes.map(v=>Bj(e.paths,r.name,v))),$f({paths:e.paths,state:r,now:t}),pc(e.paths,r.name),Ls(e.paths,r.name),Vg(e.paths,r.name),Lj(e.paths,r.name),mN(o)]);return Qy({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}Y();$r();Zr();$a();si();async function Vj(e,t){let r=K(e,t.name),i=await Ki(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await _s(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Qr(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function Fj(e,t){let r=await Vj(e,t);return{committed:r,latest:Py(r),history:xy(r)}}async function vN(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await Fj(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}$r();xr();ct();Y();var Xt=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Mj(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function Wj(e){return(await gy(e))?.change??null}function zj(e,t,r=!1,i){return cc({state:e,archiveReady:t,evidenceRetreat:r}).command}async function Jj(e,t){let r=ye(e,t.name),i=[...(await wd(r,t.brief)).findings,...(await Ug(e,t)).findings,...await wy(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ss(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await ig(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Xi({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Dy(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await yd(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function Hf(e,t,r){let i=await Wj(e)===t,n=await Ru(e,t),a=await ma(e,t),o;try{let y=await vd(e,t);if(y.status==="migration-required"&&y.state)return{name:t,phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:y.message}}if(n.status!=="available"){let y={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},C=Sf({paths:e,state:o,findings:[y]}),O=cc({state:o,findings:C});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:O.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:Ef(C),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:O,workspace:a,runtime:n,...r?.details?{findings:C}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await Ky({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await vN(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await Xi({changeDir:ye(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),C=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let de=await cn(e,o.name,o.verification_evidence);for(let ee of de.acceptanceTrace.entries)C.set(ee.acceptanceId,ee.status==="failed"?"failed":ee.status==="missing"?"missing":"satisfied")}let O=gv({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:C,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),$=O.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",O.nextCursor,"--project-root",e.projectRoot]:null;u={...O,...$?{nextPageCommand:Mj($),nextPageArgs:$}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await pc(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.findingCodes.map(C=>({code:C,message:`Native change overlap is visible in the current root: ${C}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let y=await qt(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let C=await va({paths:e,identity:y});C.state==="drifted"&&C.code&&f.push({code:C.code,message:C.message??"Native workspace binding is no longer valid"})}else{let C=await $s({paths:e,identity:y});f.push(...C.findingCodes.map(O=>({code:O,message:`Native workspace advisory changed: ${O} (${C.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let y=await pN({paths:e,state:o});v=y.freshness!=="fresh",p.push(...y.findingCodes.map(C=>({code:C,message:`Native Verify implementation scope is not current: ${C}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await Of({paths:e,name:o.name}),m.push(...h.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await Jj(e,o),...s.findings,...d,...f,...p,...l,...m].filter((y,C,O)=>O.findIndex($=>$.code===y.code&&$.path===y.path)===C),b=Sf({paths:e,state:o,findings:g}),S=b.filter(y=>!Yi(y.code)),w=o.phase==="archive"&&h?.ready===!0&&S.length===0,E=v||o.phase==="archive"&&(h?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),k=b.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),x=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=b.find(y=>y.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:k||x?null:zj(o,w,E,r?.clarificationMode),archiveReady:w,inspection:s.inspection,findingSummary:Ef(b),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:cc({state:o,findings:b,archiveReady:w,evidenceRetreat:E,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:b.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:dc,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:b.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function gN(e){let t;try{t=await Gu({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await qj.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Xt.maxChanges))throw new Error(`Native status exceeds ${Xt.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}Y();var Bf=fi(Jr(),1);Qi();pe();nt();yr();import{promises as Gj}from"node:fs";import Df from"node:path";var mc=class extends Error{};async function Lf(e,t){let r=await ae({root:e.nativeRoot,ref:Df.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:4194304,includeHash:!1}),i=(0,Bf.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new mc("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:_e(i)}}async function yN(e,t){let r;try{r=await Gj.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}if(r.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=Df.join(e.archiveDir,n.name,"comet-state.yaml");try{let o=await Lf(e,a);o.state.archived&&o.state.status==="done"&&i.push(o)}catch(o){if(o.code==="ENOENT"||o instanceof mc)continue;let s=n.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(s,`Native archive ${n.name} is unreadable: ${o.message}`)}}return i}function vc(e){return j("comet.native.status-record.v1",e)}function wN(e){let t=Df.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=zt(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=_e((0,Bf.parse)(zt(e.projectRoot,["show",`${r}:${t}`])));return vc(i)===vc(e.state)?r:null}catch{return null}}function NN(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=wN(e),i=wN(t);if(!r||!i)return!1;try{return zt(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function bN(e,t){return e.state.archived&&t.state.archived&&vc(e.state)===vc(t.state)}gt();Ea();Sa();import AN from"node:path";Ea();pe();Sa();import{promises as kN}from"node:fs";import Uj from"node:path";var Kj=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),Yj=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),Xj=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Qj=new Set(["status","summary"]);function gc(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function wc(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function Zj(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function li(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function e$(e,t,r,i){let n=gc(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=wc(n,Kj,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=gc(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=wc(o,Yj,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=gc(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=wc(c,Qj,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=gc(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:v,...h}=f,m=wc(h,Xj,`Native Supervisor child ${u}`);if(m)return m;let g=r.children[u],b=g.covers.length>0?g.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(b)||v!==void 0&&v!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!Zj(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let S=g.depends_on.length===0?"ready":"pending";if(f.status!==S)return`Native Supervisor child ${g.name} has progressed beyond its initial ${S} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function SN(e){let t=zs(e.paths,e.state.name),r;try{let c=await kN.lstat(t);if(!c.isFile()||c.isSymbolicLink())return li(t,"","Native Supervisor overlay is not a regular file");r=await kN.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:li(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return li(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=Uj.join(e.paths.changesDir,e.state.name),a;try{a=await en({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return li(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Rr(e.paths,e.state.name)}catch(c){return li(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return li(t,r,"Native Supervisor overlay disappeared during inspection");let s=e$(i,e.state,a.contract,o);return s?li(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}aa();function Qe(e,t,r){return e.language==="zh-CN"?r:t}function t$(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:Qe(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:Qe(e,"Reply A or B","回复 A 或 B"),agentInstruction:Qe(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(Qe(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(Qe(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:Qe(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:Qe(e,"Accept the result","接受结果"),agentInstruction:Qe(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(Qe(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 r$(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 i$(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:Qe(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Qe(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function CN(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ui(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function n$(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function EN(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function a$(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function o$(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 Br(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:CN({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ui("summary","--summary"),n$(e.name,e.flag)]}}function Vf(e){return[Br({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Br({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Ff(e,t,r={}){let i=a$(t)&&e.coordination_mode===void 0,n=t$(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:[ui("summary","--summary")],commandAlternatives:[Br({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:[ui("summary","--summary")],commandAlternatives:[Br({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Vf({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:[ui("summary","--summary")],commandAlternatives:[Br({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Br({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:[ui("summary","--summary")],commandAlternatives:[Br({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Vf({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:[ui("summary","--summary")],commandAlternatives:Vf({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?CN({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:o$({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?[EN("coordination-mode","--coordination-mode",bv)]:[]],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:[ui("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} ${Qe(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:[EN("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...i$(e)],userCommunication:r$(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Br({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")}}import xN from"node:path";function PN(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function qf(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:PN(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:PN(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>xN.relative(t.projectRoot,xN.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}function _N(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function IN(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function TN(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:c$(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:l$(i,r)}))]:[]]}function jN(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function RN(e,t){let r=Ee(e.projectRoot),i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:AN.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function Mf(e){let{state:t,paths:r}=e,i=qf(t),n=e.details?TN(t,null,[]):[],a=IN(e.cursor,t.state_version,0),o=n.slice(a,a+32),s=a+o.length<n.length?_N(t.state_version,0,a+o.length):null;return{schema:"comet.native.status.v2",name:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,archived:!0,archiveRef:AN.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:jN(t),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:i.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:Ff(t),...e.details?{details:{stateVersion:t.state_version,items:o,nextCursor:s,nextPageArgs:s?["comet","native","status",t.name,"--details","--cursor",s,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function s$(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function yc(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function c$(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:yc(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function l$(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:yc(e.summary,t)??""}}async function Wf(e){let t=await vy(e),r=qf(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Ca({paths:e.paths,state:t.state}),a=await SN({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Rr(e.paths,e.name,{diagnostics:!0}),s=o?{...RN(e.paths,t.state),projectRoot:"."}:RN(e.paths,t.state),c=Ff(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?s$(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:w})=>w==="pending"||w==="ready").length,h=o.children.filter(({status:w})=>w==="active"||w==="verified").length,m=o.children.filter(({status:w})=>w==="integrated"||w==="archived").length,g=o.children.filter(({status:w})=>w==="blocked"||w==="needs-reverify").length,b=o.children.filter(({status:w})=>w==="active"||w==="blocked"||w==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:yc(w.blocker,u)})),S=o.children.flatMap(({blocker:w})=>{let E=yc(w,u);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:g,active:b,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:m},risks:S,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":g>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=TN(t.state,o,u),m=IN(e.cursor,t.state.state_version,v),g=h.slice(m,m+32),b=m+g.length<h.length?_N(t.state.state_version,v,m+g.length):null;return{items:g,nextCursor:b,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:jN(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}xr();var d$=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Nc(e,t){let r=Qt.normalize(zf(e)),i=Qt.normalize(zf(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function zf(e){let t=Qt.resolve(e);try{return u$.native(t)}catch{return t}}function f$(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function $N(e){let t=[];for(let r of await gN(e))t.push({name:r,kind:await of(e,r)?"portable":"legacy"});return t}async function BN(e){let t=Qt.resolve(e),r=er(e),i=r.length>0?r:[t];i.some(o=>Nc(o,t))||i.push(t);let n=[],a=new Set;for(let o of i.map(s=>Qt.resolve(s)).sort()){let s=Nc(o,t)?t:o,c=zf(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await Ae(s);if(!u)continue;let d=await Ht(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await $N(d)})}if(n.length===0){let o=await Ae(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await Ht(e,o.native.artifact_root);n.push({projectRoot:Qt.resolve(e),config:o,paths:s,changes:await $N(s)})}for(let o of n)o.archiveErrors=[],o.archives=await yN(o.paths,(s,c)=>o.archiveErrors.push({name:s,message:c}));return n}function ON(e,t){return e.workspace.bindingState==="aligned"?0:Nc(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function LN(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:u,kind:d})=>{if(d==="portable")try{let f=await Wf({paths:u.paths,name:n});return{source:u,name:n,kind:d,workspace:f.workspace,portableStatus:f,inspectionError:null}}catch(f){return{source:u,name:n,kind:d,workspace:await ma(u.paths,n),portableStatus:null,inspectionError:f instanceof Error?f.message:String(f)}}return{source:u,name:n,kind:d,workspace:await ma(u.paths,n),portableStatus:null,inspectionError:null}})),s=t.flatMap(u=>(u.archives??[]).filter(({state:d})=>d.name===n).map(d=>{let f=Mf({paths:u.paths,...d});return{source:u,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:null,record:d}})),c=t.flatMap(u=>(u.archiveErrors??[]).filter(d=>d.name===n).map(d=>({source:u,error:d})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}if(s.length>0){for(let d of o)if(d.kind==="portable")try{d.record=await Lf(d.source.paths,Qt.join(d.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let u=s.find(d=>[...o,...s.filter(f=>!bN(d.record,f.record))].every(f=>f.record&&NN(d.record,f.record)));if(u){i.push(u);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((u,d)=>ON(u,e)-ON(d,e)||u.source.projectRoot.localeCompare(d.source.projectRoot));let l=o.filter(u=>u.workspace.bindingState==="aligned");l.length>1?i.push(...l):l.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(l[0]??o[0])}if(i.length>Xt.maxChanges)throw new Error(`Native status discovery exceeds ${Xt.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function HN(e,t){let r=t.toString(36),i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function p$(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=d$.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function DN(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?f$(r):null,nextPageArgs:r}}async function h$(e,t,r){let i=null;try{i=await qg(e.source.paths,e.name)}catch{}return i?.state?{schema:"comet.native.status.v2",name:e.name,phase:i.state.phase,status:"blocked",migrationRequired:!0,legacySchema:i.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:i.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:Hf(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function VN(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:e.record?.state.archived?Mf({paths:e.source.paths,...e.record,details:t,cursor:i}):Wf({paths:e.source.paths,name:e.name,details:t,...i?{cursor:i}:{}})}return h$(e,t,r)}async function FN(e){let t=await BN(e.projectRoot),r=(await LN(e.projectRoot,t)).filter(i=>i.name===e.name);if(r.length===0){let i=t.find(n=>Nc(n.projectRoot,e.projectRoot))??t[0];return Hf(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}if(r.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${r.map(i=>i.source.projectRoot).join(", ")}`);return VN(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function qN(e){let t=await BN(e.projectRoot),r=await LN(e.projectRoot,t),i=j("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=p$({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+Xt.maxItems).map(u=>VN(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<r.length?HN(i,f):null,v={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...DN(Qt.resolve(e.projectRoot),p),limits:{...Xt}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Xt.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?HN(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...DN(Qt.resolve(e.projectRoot),l),limits:{...Xt}}}Zn();import qa from"path";import{realpathSync as T$}from"fs";gt();var Zt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function MN(e){return e?e.command?`${Zt.next} ${e.command}`:e.ask_user?`${Zt.next} ${e.ask_user}`:null:null}function WN(e,t){let r=[e.summary],i=MN(e.next);return i&&r.push(i),e.user_message&&r.push("",Zt.relay,e.user_message),t!==void 0&&r.push("",Zt.details,JSON.stringify(t,null,2)),`${r.join(`
173
173
  `)}
174
174
  `}function zN(e,t,r){let i=[e.summary],n=MN(e.next);return n&&i.push(n),e.user_message&&i.push("",Zt.relay,e.user_message),i.push("",`${Zt.detail} ${t}`),r!==void 0&&i.push("",Zt.details,JSON.stringify(r,null,2)),i.join(`
175
- `)}Zr();Ct();st();var tJ={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};se();Nt();Y();st();vs();var fJ=16*1024*1024,pJ=256*1024,hJ=16*1024;ge();se();Gr();ge();$r();var NJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Ct();ra();ct();Y();st();vs();var oG=16*1024*1024,bc=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"},kc=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"};ge();Y();We();function V(e,t,r){return e==="zh-CN"?r:t}var Jf={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function JN(e,t){return typeof e=="string"&&Jf[e]?V(t,Jf[e].en,Jf[e].zh):typeof e=="string"?e:""}function Gf(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 w$(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 GN(e,t){let r=[];e.failed>0&&r.push(V(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(V(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(V(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=V(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function UN(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 Uf(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function y$(e,t,r){return e==="done"?V(r,"complete","已完成"):e==="await-user"?V(r,"waiting for a user decision","等待用户决定"):e==="blocked"?V(r,"paused: needs attention","已暂停,需要处理"):t?V(r,"waiting for a user decision","等待用户决定"):V(r,"ready to continue","可继续推进")}function N$(e,t,r){let i=Uf(e),n=[];r&&n.push(r);let a=V(i,`Change ${e.change}`,`需求 ${e.change}`),o=JN(e.phase,i),s=y$(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(GN(t,i));let c=e.userCommunication,l=KN(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function KN(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:V(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:V(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:V(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function b$(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function k$(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=JN(e.phase,t),n=e.status==="await-user"?V(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?V(t,"paused","已暂停"):e.status==="done"?V(t,"complete","已完成"):V(t,"in progress","进行中"),a=Gf(e.acceptance)?`${V(t,", ",",")}${GN(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function S$(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 E$(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 C$(e){if(e.healthy){let i=e.repaired?V("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):V("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=x$(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:V("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:V("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function x$(e){return UN(e)?KN(e,Uf(e)):void 0}function YN(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(E$(t))return C$(t);if(b$(t)){let i=S$(t.items);return{summary:[t.total===t.items.length?V(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):V(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>k$(a,i))].join(`
176
- `)}}let r=t.continuation;if(UN(r))return N$(r,P$(t),R$(t,Uf(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:V(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 P$(e){if(Gf(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Gf(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return w$(r.acceptance)}return null}function R$(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return V(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?V(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function XN(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:V("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:V("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:V("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:V("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:V("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:V("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:V("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:V("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:V("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Cd();var QN=["--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."],Yf=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:QN,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>
177
- 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>]
175
+ `)}Zr();xt();ct();var tJ={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};se();bt();Y();ct();vs();var fJ=16*1024*1024,pJ=256*1024,hJ=16*1024;ge();se();Gr();ge();$r();var NJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});xt();ra();lt();Y();ct();vs();var oG=16*1024*1024,bc=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"},kc=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"};ge();Y();We();function V(e,t,r){return e==="zh-CN"?r:t}var Jf={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function JN(e,t){return typeof e=="string"&&Jf[e]?V(t,Jf[e].en,Jf[e].zh):typeof e=="string"?e:""}function Gf(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 w$(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 GN(e,t){let r=[];e.failed>0&&r.push(V(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(V(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(V(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=V(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function UN(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 Uf(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function y$(e,t,r){return e==="done"?V(r,"complete","已完成"):e==="await-user"?V(r,"waiting for a user decision","等待用户决定"):e==="blocked"?V(r,"paused: needs attention","已暂停,需要处理"):t?V(r,"waiting for a user decision","等待用户决定"):V(r,"ready to continue","可继续推进")}function N$(e,t,r){let i=Uf(e),n=[];r&&n.push(r);let a=V(i,`Change ${e.change}`,`需求 ${e.change}`),o=JN(e.phase,i),s=y$(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(GN(t,i));let c=e.userCommunication,l=KN(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function KN(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:V(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:V(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:V(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function b$(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function k$(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=JN(e.phase,t),n=e.status==="await-user"?V(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?V(t,"paused","已暂停"):e.status==="done"?V(t,"complete","已完成"):V(t,"in progress","进行中"),a=Gf(e.acceptance)?`${V(t,", ",",")}${GN(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function S$(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 E$(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 C$(e){if(e.healthy){let i=e.repaired?V("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):V("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=x$(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:V("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:V("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function x$(e){return UN(e)?KN(e,Uf(e)):void 0}function YN(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(E$(t))return C$(t);if(b$(t)){let i=S$(t.items);return{summary:[t.total===t.items.length?V(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):V(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>k$(a,i))].join(`
176
+ `)}}let r=t.continuation;if(UN(r))return N$(r,P$(t),R$(t,Uf(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:V(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 P$(e){if(Gf(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Gf(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return w$(r.acceptance)}return null}function R$(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return V(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?V(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function XN(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:V("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:V("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:V("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:V("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:V("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:V("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:V("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:V("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:V("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Cd();var QN=["--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."],Yf=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:QN,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>
177
+ 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>]
178
178
  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>]
179
179
  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]
180
180
  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 Kf(e,t){return`${e}:
@@ -182,11 +182,11 @@ ${t.map(r=>` ${r}`).join(`
182
182
  `)}`}function A$(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Yf[r]||t.length>1&&Yf[t[0]]?.subcommands?r:t[0]}function _$(e=[]){let t=A$(e),r=Yf[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Kf("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...QN];return n&&n.length>0&&i.push("",Kf("Options",n)),i.push("",`Output:
183
183
  ${r.output}`),r.examples&&i.push("",Kf("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
184
184
  `)}
185
- `}}var I$=_$().usage;var xG=10*1024*1024,It=class extends Error{};function Ma(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new It(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Sc(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new It(`${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 It(`${t} requires a value`);return e.splice(i,2),n}function eb(e){if(e.length>0)throw new It(`Unexpected argument: ${e[0]}`)}function Xf(e,t){let r=qa.normalize(ZN(e)),i=qa.normalize(ZN(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ZN(e){let t=qa.resolve(e);try{return T$.native(t)}catch{return t}}function j$(e){let t=qa.resolve(e),r=Ee(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=Ee(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Xf(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Xf(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Xf(process.cwd(),r.currentWorktreeRoot)?qa.resolve(process.cwd()):r.currentWorktreeRoot}async function tb(e){return e?j$(e):xu(process.cwd())}function rb(e){return JSON.stringify(e,null,2)+`
186
- `}function ib(e,t,r){return{command:e,exitCode:0,data:t,text:r??rb(t)}}function $$(e,t){if(t instanceof It)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof bc)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 kc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Hs)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 ga)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 Ws)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ds)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 Dr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Fa)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 nb(e,t){let r=$$(e,t),i=r.error;if(!i)return r;let n=XN({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function ab(e,t,r=!1){let i=e.envelope??YN(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}})+`
185
+ `}}var I$=_$().usage;var xG=10*1024*1024,Tt=class extends Error{};function Ma(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Tt(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Sc(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Tt(`${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 Tt(`${t} requires a value`);return e.splice(i,2),n}function eb(e){if(e.length>0)throw new Tt(`Unexpected argument: ${e[0]}`)}function Xf(e,t){let r=qa.normalize(ZN(e)),i=qa.normalize(ZN(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ZN(e){let t=qa.resolve(e);try{return T$.native(t)}catch{return t}}function j$(e){let t=qa.resolve(e),r=Ee(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=Ee(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Xf(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Xf(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Xf(process.cwd(),r.currentWorktreeRoot)?qa.resolve(process.cwd()):r.currentWorktreeRoot}async function tb(e){return e?j$(e):xu(process.cwd())}function rb(e){return JSON.stringify(e,null,2)+`
186
+ `}function ib(e,t,r){return{command:e,exitCode:0,data:t,text:r??rb(t)}}function $$(e,t){if(t instanceof Tt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof bc)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 kc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Hs)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 ga)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 Ws)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ds)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 Dr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Fa)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 nb(e,t){let r=$$(e,t),i=r.error;if(!i)return r;let n=XN({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function ab(e,t,r=!1){let i=e.envelope??YN(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}})+`
187
187
  `}:e.error?{exitCode:e.exitCode,stderr:i?zN(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:WN(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==rb(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
188
188
  ${Zt.details}
189
189
  ${JSON.stringify(e.data,null,2)}
190
- `}:{exitCode:e.exitCode,stdout:e.text}}async function ob(e,t){let r=Ma(e,"--details"),i=Sc(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new It("status --details requires a change name");if(i&&n&&!r)throw new It("--cursor for a named status requires --details");eb(e);let a=n?await FN({projectRoot:t,name:n,details:r,...i?{detailsCursor:i}:{}}):await qN({projectRoot:t,...i?{cursor:i}:{}});return ib("status",a)}async function sb(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{Ma(n,"--json"),Ma(n,"--verbose"),c=Sc(n,"--project-root");let d=[...n,...a],f=await tb(c);l=await t(d,f)}catch(d){l=nb(e,d)}let u=ab(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
190
+ `}:{exitCode:e.exitCode,stdout:e.text}}async function ob(e,t){let r=Ma(e,"--details"),i=Sc(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new Tt("status --details requires a change name");if(i&&n&&!r)throw new Tt("--cursor for a named status requires --details");eb(e);let a=n?await FN({projectRoot:t,name:n,details:r,...i?{detailsCursor:i}:{}}):await qN({projectRoot:t,...i?{cursor:i}:{}});return ib("status",a)}async function sb(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{Ma(n,"--json"),Ma(n,"--verbose"),c=Sc(n,"--project-root");let d=[...n,...a],f=await tb(c);l=await t(d,f)}catch(d){l=nb(e,d)}let u=ab(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
191
191
  `)?"":`
192
192
  `)),u.exitCode}process.exitCode=await sb("status",ob);