@rpamis/comet 0.4.0-beta.13 → 0.4.0-beta.14

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 (87) hide show
  1. package/assets/manifest.json +1 -1
  2. package/assets/skills/comet/scripts/comet-archive.mjs +66 -66
  3. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
  4. package/assets/skills/comet/scripts/comet-guard.mjs +88 -88
  5. package/assets/skills/comet/scripts/comet-handoff.mjs +68 -68
  6. package/assets/skills/comet/scripts/comet-hook-guard.mjs +62 -62
  7. package/assets/skills/comet/scripts/comet-hook-router.mjs +64 -64
  8. package/assets/skills/comet/scripts/comet-resume-probe.mjs +55 -55
  9. package/assets/skills/comet/scripts/comet-runtime.mjs +134 -134
  10. package/assets/skills/comet/scripts/comet-state.mjs +67 -67
  11. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +6 -6
  12. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +39 -39
  13. package/assets/skills/comet-native/scripts/comet-native-check.mjs +45 -45
  14. package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +35 -35
  15. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +33 -33
  16. package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +7 -7
  17. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +7 -7
  18. package/assets/skills/comet-native/scripts/comet-native-init.mjs +6 -6
  19. package/assets/skills/comet-native/scripts/comet-native-new.mjs +44 -44
  20. package/assets/skills/comet-native/scripts/comet-native-next.mjs +27 -27
  21. package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +24 -24
  22. package/assets/skills/comet-native/scripts/comet-native-root.mjs +31 -31
  23. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +43 -43
  24. package/assets/skills/comet-native/scripts/comet-native-select.mjs +41 -41
  25. package/assets/skills/comet-native/scripts/comet-native-show.mjs +7 -7
  26. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +51 -51
  27. package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
  28. package/dist/app/commands/i18n.d.ts +1 -1
  29. package/dist/app/commands/i18n.d.ts.map +1 -1
  30. package/dist/app/commands/i18n.js +90 -0
  31. package/dist/app/commands/i18n.js.map +1 -1
  32. package/dist/app/commands/init.d.ts.map +1 -1
  33. package/dist/app/commands/init.js +2 -0
  34. package/dist/app/commands/init.js.map +1 -1
  35. package/dist/app/commands/project-scope-selection.d.ts +2 -1
  36. package/dist/app/commands/project-scope-selection.d.ts.map +1 -1
  37. package/dist/app/commands/project-scope-selection.js +5 -7
  38. package/dist/app/commands/project-scope-selection.js.map +1 -1
  39. package/dist/app/commands/uninstall.d.ts +6 -0
  40. package/dist/app/commands/uninstall.d.ts.map +1 -1
  41. package/dist/app/commands/uninstall.js +197 -110
  42. package/dist/app/commands/uninstall.js.map +1 -1
  43. package/dist/app/commands/update.d.ts.map +1 -1
  44. package/dist/app/commands/update.js +39 -1
  45. package/dist/app/commands/update.js.map +1 -1
  46. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  47. package/dist/domains/comet-classic/classic-layout-initialization.js +8 -4
  48. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  49. package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
  50. package/dist/domains/comet-classic/classic-layout.js +1 -0
  51. package/dist/domains/comet-classic/classic-layout.js.map +1 -1
  52. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  53. package/dist/domains/comet-entry/init-workflow.js +2 -3
  54. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  55. package/dist/domains/integrations/openspec.d.ts.map +1 -1
  56. package/dist/domains/integrations/openspec.js +5 -2
  57. package/dist/domains/integrations/openspec.js.map +1 -1
  58. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  59. package/dist/domains/skill/platform-install.js +32 -0
  60. package/dist/domains/skill/platform-install.js.map +1 -1
  61. package/dist/domains/skill/uninstall.d.ts +6 -2
  62. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  63. package/dist/domains/skill/uninstall.js +142 -18
  64. package/dist/domains/skill/uninstall.js.map +1 -1
  65. package/dist/domains/workflow-contract/contained-atomic-write.d.ts +3 -0
  66. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  67. package/dist/domains/workflow-contract/contained-atomic-write.js +15 -2
  68. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  69. package/dist/domains/workflow-contract/index.d.ts +1 -1
  70. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  71. package/dist/domains/workflow-contract/index.js +1 -1
  72. package/dist/domains/workflow-contract/index.js.map +1 -1
  73. package/dist/domains/workflow-contract/project-config-reader.d.ts +2 -0
  74. package/dist/domains/workflow-contract/project-config-reader.d.ts.map +1 -1
  75. package/dist/domains/workflow-contract/project-config-reader.js.map +1 -1
  76. package/dist/domains/workflow-contract/project-config-writer.d.ts.map +1 -1
  77. package/dist/domains/workflow-contract/project-config-writer.js +3 -2
  78. package/dist/domains/workflow-contract/project-config-writer.js.map +1 -1
  79. package/dist/domains/workflow-contract/project-config.d.ts +1 -0
  80. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  81. package/dist/domains/workflow-contract/project-config.js +9 -4
  82. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  83. package/dist/platform/install/platforms.d.ts +2 -0
  84. package/dist/platform/install/platforms.d.ts.map +1 -1
  85. package/dist/platform/install/platforms.js +1 -0
  86. package/dist/platform/install/platforms.js.map +1 -1
  87. package/package.json +1 -1
@@ -139,13 +139,13 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
139
139
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
140
140
  `,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){zi(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ve(i.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(mc(i.key)&&!ve(i.sep,"newline")){let o=Xe(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(ve(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Xe(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):ve(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{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);r||i.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!ve(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){zi(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||ve(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?e.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=Vi(n),a=Xe(r);pc(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(`
141
141
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
142
- `,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Vi(e),n=Xe(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Vi(e),n=Xe(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};vc.Parser=Xr});var bc=w(Ot=>{"use strict";var gc=Mr(),zh=Et(),_t=Pt(),Wh=Hn(),Jh=C(),Kh=Yr(),wc=Qr();function yc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Kh.LineCounter||null,prettyErrors:e}}function Gh(t,e={}){let{lineCounter:i,prettyErrors:n}=yc(e),r=new wc.Parser(i?.addNewLine),a=new gc.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(_t.prettifyError(t,i)),s.warnings.forEach(_t.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Nc(t,e={}){let{lineCounter:i,prettyErrors:n}=yc(e),r=new wc.Parser(i?.addNewLine),a=new gc.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new _t.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(_t.prettifyError(t,i)),o.warnings.forEach(_t.prettifyError(t,i))),o}function Uh(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=Nc(t,i);if(!r)return null;if(r.warnings.forEach(a=>Wh.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Yh(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Jh.isDocument(t)&&!n?t.toString(i):new zh.Document(t,n,i).toString(i)}Ot.parse=Uh;Ot.parseAllDocuments=Gh;Ot.parseDocument=Nc;Ot.stringify=Yh});var ea=w(P=>{"use strict";var Xh=Mr(),Qh=Et(),Zh=wr(),Zr=Pt(),ep=ct(),ge=C(),tp=de(),ip=T(),np=pe(),rp=me(),ap=Bi(),op=Gr(),sp=Yr(),cp=Qr(),Wi=bc(),Sc=rt();P.Composer=Xh.Composer;P.Document=Qh.Document;P.Schema=Zh.Schema;P.YAMLError=Zr.YAMLError;P.YAMLParseError=Zr.YAMLParseError;P.YAMLWarning=Zr.YAMLWarning;P.Alias=ep.Alias;P.isAlias=ge.isAlias;P.isCollection=ge.isCollection;P.isDocument=ge.isDocument;P.isMap=ge.isMap;P.isNode=ge.isNode;P.isPair=ge.isPair;P.isScalar=ge.isScalar;P.isSeq=ge.isSeq;P.Pair=tp.Pair;P.Scalar=ip.Scalar;P.YAMLMap=np.YAMLMap;P.YAMLSeq=rp.YAMLSeq;P.CST=ap;P.Lexer=op.Lexer;P.LineCounter=sp.LineCounter;P.Parser=cp.Parser;P.parse=Wi.parse;P.parseAllDocuments=Wi.parseAllDocuments;P.parseDocument=Wi.parseDocument;P.stringify=Wi.stringify;P.visit=Sc.visit;P.visitAsync=Sc.visitAsync});var ba=Oa(ea(),1);import{promises as Om}from"fs";import Le from"path";import{createHash as dp}from"node:crypto";import{promises as U}from"node:fs";import V from"node:path";import{TextDecoder as hp}from"node:util";var lp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),up=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function fp(t){return t.toLowerCase().startsWith(".env")}function jt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>fp(n))?"environment-file":i.some(n=>up.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>lp.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function we(t){return t!==0&&t!==0n&&t!=="0"}function G(t,e){return we(t.dev)&&we(e.dev)&&we(t.ino)&&we(e.ino)}function I(t,e){let i=we(t.dev)&&we(e.dev);if(i&&t.dev!==e.dev)return!1;let n=we(t.ino)&&we(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Ki=1024*1024;function ta(t,e){let i=V.relative(t,e);return i===""||!V.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${V.sep}`)}function pp(t){let e=V.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||V.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=jt(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function mp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function vp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ji(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return G(i,n)?I(i,n):I(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function kc(t){let e=await U.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await U.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function gp(t,e){let i=V.resolve(t),n=V.resolve(e);if(!ta(i,n))throw new Error("Native artifact path is outside its root");let r=[await kc(i)],a=i;for(let o of V.relative(i,n).split(V.sep).filter(Boolean)){a=V.join(a,o);let s=await kc(a);if(!ta(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Ec(t){for(let e of t){let i=await U.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!vp(e,i)||await U.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Y(t){let e=pp(t.ref),i=mp(t.maxBytes??Ki),n=V.resolve(t.root,...e.split("/")),r=await gp(t.root,V.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await U.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await U.realpath(n);if(!ta(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await U.open(n,"r");try{let[c,l,d]=await Promise.all([s.stat(),U.lstat(n),U.realpath(n)]);if(await Ec(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!Ji(a,c)||!Ji(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let S=i+1-f,k=await s.read(m,0,Math.min(m.length,S),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(m.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([s.stat(),U.lstat(n),U.realpath(n)]);if(await Ec(r),!h.isFile()||h.isSymbolicLink()||p!==o||!Ji(c,g)||!Ji(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,f),N;try{N=new hp("utf-8",{fatal:!0}).decode(y)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:S})}return{ref:e,size:f,hash:dp("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var na=Oa(ea(),1);import Gi from"path";var Xi=64*1024,Ui=1024,Yi=64,ra=5,wp=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],F={include:["**/*"],exclude:[...wp],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function yp(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Gi.posix.isAbsolute(i)||Gi.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function Te(t){let e=yp(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Rc(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function aa(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Gi.posix.isAbsolute(n)||Gi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function $t(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Pc(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Qi(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ui)throw new Error(`${e} exceeds ${Ui} characters`);let i=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?i+=1:t[n]==="*"&&(i+=1,t[n+1]==="*"&&(n+=1));if(i>Yi)throw new Error(`${e} contains more than ${Yi} wildcard tokens`);return t}function Cc(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>Qi(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function ia(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function Np(t){if(t===void 0)return{...F,include:[...F.include],exclude:[...F.exclude]};let e=$t(t,"native.snapshot");return{include:Cc(e.include,"native.snapshot.include",F.include),exclude:Cc(e.exclude,"native.snapshot.exclude",F.exclude),max_files:ia(e.max_files,F.max_files,"native.snapshot.max_files"),max_total_bytes:ia(e.max_total_bytes,F.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ia(e.max_duration_ms,F.max_duration_ms,"native.snapshot.max_duration_ms")}}function bp(t){if(t===void 0)return;let e=$t(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=$t(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=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 d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:Te(n),toArtifactRoot:Te(r),stage:a,...o?{cleanup:o}:{}}}function Sp(t){let e=$t(t,"native");if(typeof e.artifact_root!="string")throw new Error("native.artifact_root must be a string");let i=e.clarification_mode??"sequential";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let n=e.archive_confirmation??"automatic";if(n!=="automatic"&&n!=="required")throw new Error("native.archive_confirmation must be automatic or required");let r=e.max_verify_failures??ra;if(!Number.isSafeInteger(r)||r<1)throw new Error("native.max_verify_failures must be a positive integer");let a=bp(e.pending_root_move);return{artifact_root:Te(e.artifact_root),language:Pc(e.language,"en","native.language"),clarification_mode:i,archive_confirmation:n,max_verify_failures:r,snapshot:Np(e.snapshot),...a?{pending_root_move:a}:{}}}function kp(t){let e=$t(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Rc(e.artifact_layout),language:Pc(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Ep(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Cp(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function Zi(t,e={}){let i=(0,na.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=Ep(r.ambient_resume),o=r.native===void 0?void 0:Sp(r.native),s=r.classic===void 0?void 0:kp(r.classic),c=Cp(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function oa(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Te(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ra,snapshot:{...F,include:[...F.include],exclude:[...F.exclude]}}}}import{createHash as Pp}from"crypto";import{promises as nn}from"fs";import ye from"path";import{constants as en,promises as Ie}from"fs";var ne=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function sa(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Ac(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Ht(t){return{dev:t.dev,ino:t.ino,birthtime:sa(t)}}function tn(t,e){let i=Ht(t),n=Ht(e);return G(i,n)?I(i,n):I(i,n)&&sa(t)===sa(e)&&Ac(t)===Ac(e)&&t.size===e.size}async function Lt(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Ie.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new ne("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ne("too-large",`${n} exceeds ${e} bytes`);let o=await Ie.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Ht(a)});let s=process.platform==="win32"?en.O_RDONLY:en.O_RDONLY|en.O_NOFOLLOW|en.O_NONBLOCK,c;try{c=await Ie.open(t,s)}catch(l){throw l.code==="ELOOP"?new ne("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!tn(a,l)||!tn(a,d))throw new ne("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Ht(l)}),await i.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-m,{bytesRead:S}=await c.read(g,0,Math.min(g.length,N),null);if(S===0)break;if(m+=S,m>e)throw new ne("too-large",`${n} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!tn(a,h)||!tn(a,p))throw new ne("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Ht(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:y}}finally{await c.close()}}function Rp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ca(t,e){let i=ye.relative(t,e);return i===""||!ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ye.sep}`)}async function xc(t,e){let i=ye.resolve(t),n=await nn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return nn.realpath(i)}async function Tc(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=ye.join(r,i[a]);let o;try{o=await nn.lstat(r)}catch(d){if(Rp(d))return{exists:!1,kind:"missing"};throw d}let s=ye.relative(t,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await nn.realpath(r);if(!ca(e,l))throw new Error(`${n.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 Mt(t,e,i){let n=aa(e,i.label),r=ye.resolve(t),a=await xc(r,i.label),o=n.split("/"),s=ye.resolve(r,...o);if(!ca(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Tc(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Qe(t,e,i,n){let r=await Mt(t,e,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await xc(r.projectRoot,n.label);return Lt(r.target,i,{...n,verify:async(o,s)=>{if(!ca(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Tc(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var Dt=".comet/config.yaml";function Ap(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function la(t,e={}){return(await rn(t,e)).document}async function xp(t){try{return(await Qe(t,Dt,Xi,{label:Dt})).bytes}catch(e){if(Ap(e))return null;throw e}}function Tp(t){return t?{exists:!0,sha256:Pp("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function rn(t,e={}){let i=await xp(t);return{document:i?Zi(i.toString("utf8"),e):null,identity:Tp(i)}}var Cw=16*1024;import{promises as Ze}from"fs";import A from"path";import jp from"os";var an=".comet/config.yaml";async function fa(t){try{return await Ze.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function $p(t){try{let e=await Ze.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Ft(t,e){let i=A.relative(t,e);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Bt(t){let e=[],i=t;for(;!await fa(i);){let r=A.dirname(i);if(r===i)break;e.push(A.basename(i)),i=r}let n=await Ze.realpath(i);return A.resolve(n,...e.reverse())}async function jc(t){try{return(await Ze.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function on(t){let e=A.resolve(t);try{(await Ze.stat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=A.resolve(jp.homedir());for(;;){if(!(e===n&&i!==n)){let o=A.join(e,...an.split("/")),s=e===i||await $p(o);if(await fa(o)&&s)return e}if(await fa(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return i;e=a}}function sn(t){return Te(t)}async function Hp(t,e){let i=sn(e),n=A.resolve(t,...i.split("/")),r=await Ze.realpath(t),a=await Bt(n);if(!Ft(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function da(t,e){let i=sn(e),n=await Hp(t,i),r=A.join(n,"comet");if(await jc(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Bt(n),Bt(r)]);if(!Ft(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:A.resolve(t),configFile:A.join(t,...an.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:A.join(r,"specs"),changesDir:A.join(r,"changes"),archiveDir:A.join(r,"archive"),runtimeDir:A.join(r,"runtime"),locksDir:A.join(r,"runtime","locks"),transactionsDir:A.join(r,"runtime","transactions")}}function re(t,e){return Ft(A.resolve(t),A.resolve(e))}async function j(t,e){let i=A.resolve(t),n=A.resolve(e);if(!Ft(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await jc(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([Bt(i),Bt(n)]);if(!Ft(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var cn=Qi;function Mp(t="docs",e="en"){return oa(t,e)}async function qt(t){let e=(await la(t))?.config??null;return e?.native?e:null}async function $c(t){let e=await on(t.startPath),i=await qt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${an} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=t.explicitArtifactRoot?sn(t.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??Mp(n??"docs"),a=await da(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{AsyncLocalStorage as Dp}from"async_hooks";var Uw=16*1024;var Yw=new Dp;import{TextDecoder as Kp}from"util";import{createHash as Fp}from"node:crypto";import{constants as ln,promises as X}from"node:fs";import Q from"node:path";import{TextDecoder as Bp}from"node:util";function fn(t,e){let i=Q.relative(t,e);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function qp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Vp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function zp(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function un(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function pa(t,e){let i=await X.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await X.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Hc(t,e,i){let n=Q.resolve(t),r=Q.resolve(e);if(!fn(n,r))throw new Error(`${i} is outside its managed root`);let a=[await pa(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await Ne(a,i),o=Q.join(o,s);let c=await pa(o,i);if(!fn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ne(a,i),a}async function Ne(t,e){for(let i of t){let n=await X.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Vp(i,n)||await X.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Wp(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function et(t){let e=qp(t.maxBytes),i=Q.resolve(t.file),n=await Hc(t.root,Q.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(d=>pa(Q.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ne(n,t.label);let a=await X.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=zp(a),s=await X.realpath(i);if(!fn(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(d=>fn(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ln.O_RDONLY:ln.O_RDONLY|ln.O_NOFOLLOW|ln.O_NONBLOCK,l=await X.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([X.lstat(i),X.realpath(i)]);if(await Ne(n,t.label),await Ne(r,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!un(o,d)||!un(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await Wp(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([l.stat(),X.lstat(i),X.realpath(i)]);if(await Ne(n,t.label),await Ne(r,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!un(o,g)||!un(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:Fp("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function Lc(t){let e=await et(t),i;try{i=new Bp("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}async function ma(t){let e=await Hc(t.root,t.directory,t.label);return{verify:()=>Ne(e,t.label)}}var dy=256*1024,hy=1024*1024,py=16*1024;var my=64*1024*1024;var vy=new Kp("utf-8",{fatal:!0});import hn from"path";import{createHash as Up}from"crypto";function B(t){return Up("sha256").update(t).digest("hex")}var jy={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Xp=1e3,Qp=8*1024*1024,Zp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,em=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),tm=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),im=new Set(["schema","include","exclude","hash"]),nm=new Set(["provider","gitSelection","physicalSelection","projection"]),rm=new Set(["provider","selection"]),am=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),om=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),sm=new Set(["schema","status","before","after"]),cm=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),lm=new Set(["path","hash","size","type","gitObjectId"]),um=new Set(["path","size","type","reason"]),fm=new Set(["ref","hash","count"]),dm=new Set(["change-created","legacy-migration","explicit"]),hm=new Set(["file","directory","other"]),pm=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"]),pn=/^[a-f0-9]{64}$/u,mm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var $y=64*1024,Hy=64*1024;var Ly={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},My={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function dn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var Dy=(1n<<256n)-1n;function vm(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function gm(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
143
- `)}function wm(t,e){return B(`comet.native.snapshot-policy.v1
144
- ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function ga(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function ym(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function qc(t){let e=cn(t,"Native snapshot pattern"),i=[];for(let n=0;n<e.length;n+=1){let r=e[n];r==="*"&&e[n+1]==="*"?(n+=1,e[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?ym(r):void 0;if(a&&!a())return!1;let o=ga(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=i[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=ga(i,c,a),o===null||o.size===0)return!1}return ga(i,o,a)?.has(i.length)??!1}}function Nm(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>cn(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>cn(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=wm(e,i);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:n},includeMatchers:e.map(qc),excludeMatchers:i.map(qc),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function z(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function W(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function it(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ae(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Wc(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=hn.posix.normalize(t);if(i!==t||hn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function bm(t,e){let i=z(t,`Native snapshot entry ${e}`);W(i,lm,`Native snapshot entry ${e}`);let n=Wc(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:ae(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!mm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function Sm(t,e){let i=z(t,`Native snapshot omission ${e}`);if(W(i,um,`Native snapshot omission ${e}`),!hm.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!pm.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Wc(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:ae(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function km(t){let e=z(t,"Native snapshot omission overflow");if(W(e,fm,"Native snapshot omission overflow"),typeof e.hash!="string"||!pn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:it(e.count,"Native snapshot omission overflow count")}}function tt(t,e){let i=z(t,e);if(W(i,om,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=ae(i.recordCount,`${e} recordCount`),r=ae(i.storedRecordCount,`${e} storedRecordCount`),a=ae(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function Vc(t){let e=z(t,"Native Git selection evidence");if(W(e,am,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=tt(e.stageBefore,"Native Git selection stageBefore"),n=tt(e.combined,"Native Git selection combined"),r=tt(e.stageAfter,"Native Git selection stageAfter"),a=tt(e.finalStageBefore,"Native Git selection finalStageBefore"),o=tt(e.finalCombined,"Native Git selection finalCombined"),s=tt(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!dn(i,r)||!dn(r,a)||!dn(n,o)||!dn(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function zc(t,e){let i=z(t,e);if(W(i,cm,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=ae(i.visitedNodeCount,`${e} visitedNodeCount`),r=ae(i.recordCount,`${e} recordCount`),a=ae(i.storedRecordCount,`${e} storedRecordCount`),o=ae(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Em(t){let e=z(t,"Native physical selection evidence");if(W(e,sm,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=zc(e.before,"Native physical selection before"),n=zc(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!vm(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function Jc(t){let e=z(t,"Native content snapshot manifest");if(W(e,em,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!dm.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=z(e.capture,"Native content snapshot capture");if(W(v,nm,"Native content snapshot capture"),v.provider!=="git"&&v.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=v.gitSelection===void 0?void 0:Vc(v.gitSelection),b=v.physicalSelection===void 0?void 0:Em(v.physicalSelection),x=null;if(v.projection!==void 0){let D=z(v.projection,"Native content snapshot projection");if(W(D,rm,"Native content snapshot projection"),D.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");x={provider:"git",...D.selection===void 0?{}:{selection:Vc(D.selection)}}}if(v.provider==="git"){if(b||x)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&x)throw new Error("Native physical-tree capture cannot combine selection and projection");i=x?{provider:"physical-tree",projection:x}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=z(e.limits,"Native content snapshot limits");W(n,tm,"Native content snapshot limits");let r={maxFiles:it(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:it(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:it(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:it(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:it(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=z(e.policy,"Native snapshot policy");if(W(v,im,"Native snapshot policy"),v.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(v.include)||!Array.isArray(v.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Nm({include:v.include,exclude:v.exclude,hash:v.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(bm),s=e.omitted.map(Sm),c=ae(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:km(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(v=>v.size>r.maxFileBytes)||o.reduce((v,R)=>v+R.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(v=>v.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Xp||c<s.length)throw new Error("Native content snapshot omission count is invalid");let d=c-s.length;if(d===0&&l||d>0&&l?.count!==d)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(v=>v.reason==="git-enumeration-limit"),f=s.filter(v=>v.reason==="git-selection-changed");for(let v of[...u,...f])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let m=i?.provider==="git"?i.gitSelection:i?.projection?.selection,g=m?.status==="overflow"||m?.status==="overflow-and-changed",h=m?.status==="changed"||m?.status==="overflow-and-changed";if(g!==(u.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 p=s.filter(v=>v.reason==="physical-enumeration-limit"),y=s.filter(v=>v.reason==="physical-selection-changed");for(let v of[...p,...y])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,S=N?.status==="overflow"||N?.status==="overflow-and-changed",k=N?.status==="changed"||N?.status==="overflow-and-changed";if(S!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(gm(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Cm(t,e){if(!Zp.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=hn.join(t.changesDir,e);if(!re(t.changesDir,i))throw new Error("Native change path escaped");return hn.join(i,"runtime","baseline-manifest.json")}async function Kc(t,e){let i=Cm(t,e);await j(t.nativeRoot,i);try{let n=await Lc({root:t.nativeRoot,file:i,maxBytes:Qp,label:"Native baseline snapshot manifest"});return Jc(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var IN=256*1024;var zN={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};var ib=16*1024;var je="comet.native.v3",$e="comet.native.v2",He="comet.native.v1";var Uc=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],jm=new Set(Uc),Yc=new Set([...Uc,"minimum_runtime_version","revision"]),$m=new Set([...Yc,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Hm=new Set(["capability","operation","source","base_hash"]),Lm=new Set(["shape","build","verify","archive"]),Mm=new Set(["implicit","confirmed"]),Dm=new Set(["pending","pass","fail"]),Me="comet-state.yaml",ya=/^[a-f0-9]{64}$/u,Xc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Fm=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Na=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Se=class extends Error{constructor(i,n){super(i!==je||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},mn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},vn=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;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"},kb=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
145
- `);function zt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Qc(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Wt(t){if(!Xc.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Bm(t){if(!Xc.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Zc(t,e){if(t.length===0||Le.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function qm(t,e){let i=zt(t,`spec_changes[${e}]`);if(Qc(i,Hm,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Bm(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&Zc(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!ya.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!ya.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function Vm(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Sa(t,e){if(Qc(t,e,Me),typeof t.name!="string")throw new Error("Native change name is required");if(Wt(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!Lm.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!Mm.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(qm),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!Dm.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Zc(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!Vm(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ka(t){let e=zt(t,Me);if(e.schema!==He)throw new Error(`Expected ${He}`);return{schema:He,...Sa(e,jm)}}function Vt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function wa(t,e,i){if(t===null)return null;let n=typeof t=="string"?Fm.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function zm(t){if(t==null)return null;if(typeof t!="string"||!ya.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Wm(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Ea(t){let e=zt(t,Me);if(e.schema!==$e)throw new Error(`Expected ${$e}`);if(Vt(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${$e} minimum_runtime_version must be 2`);return{schema:$e,minimum_runtime_version:2,revision:Vt(e.revision,"Native v2 revision"),...Sa(e,Yc)}}function Ca(t){let e=zt(t,Me);if(e.schema!==je){if(e.schema===He||e.schema===$e){let o=e.schema===He?ka(e):Ea(e);throw new Na(o.name,o.schema)}throw new Se(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Vt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Se(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Vt(e.revision,"Native revision"),r=Sa(e,$m),a=zm(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:je,minimum_runtime_version:3,revision:n,verification_protocol:Wm(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:wa(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:wa(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:wa(e.partial_allowance,"Native partial_allowance","allowances")}}function Jm(t){let e=zt(t,Me);if(e.schema===He){let r=ka(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${je}`}}if(e.schema===$e){let r=Ea(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${je}`}}if(e.schema!==je){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Se(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Vt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Se(e.schema,i).message};let n=Ca(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function H(t,e){Wt(e);let i=Le.join(t.changesDir,e);if(!re(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Ra(t,e){let i=Le.join(H(t,e),"runtime","schema-migration.json");await j(t.nativeRoot,i);try{return await Om.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var Km=256*1024;async function Gm(t,e=Le.dirname(t)){let i=Le.relative(e,t).split(Le.sep).join("/"),n=await Y({root:e,ref:i,maxBytes:Km}),r=(0,ba.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function el(t,e){let i=Le.join(H(t,e),Me);await j(t.nativeRoot,i);let n=Jm(await Gm(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ra(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await Um(t,n.state),n)}async function Um(t,e){if(await Kc(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}import{createHash as Ym}from"crypto";function Z(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Xm(t,e){e.has(t)&&Z("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;n<t.length;n+=1)Object.prototype.hasOwnProperty.call(t,n)||Z("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Z("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Z("symbol properties are not supported"),`[${t.map(n=>Pa(n,e)).join(",")}]`}finally{e.delete(t)}}function Qm(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Z("only plain objects are supported"),e.has(t)&&Z("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Z("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Z("accessor properties are not supported"),`${JSON.stringify(o)}:${Pa(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Pa(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Z("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Xm(t,e):Qm(t,e);case"bigint":case"function":case"symbol":case"undefined":return Z(`${typeof t} values are not supported`)}return Z("unsupported value type")}function Aa(t){return Pa(t,new Set)}function ee(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Ym("sha256").update(`${t}
146
- ${Aa(e)}`).digest("hex")}var Ab=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),tl=Object.freeze({maxCriteria:1024});var $b={maxAcceptanceCriteria:tl.maxCriteria};var De={maxSpecs:64,maxFileBytes:Ki,maxTotalBytes:4*1024*1024};import{promises as fl}from"fs";import dl from"path";var Zm=["Outcome","Scope","Non-goals","Acceptance examples"],Wb=[...Zm,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var iS={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var nl=1024*1024;var al={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:[]},tv=B("comet-native-runtime:v3:semantic-repair-budget"),TS=[{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];var ll=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],lk=new Set(ll),ov=new Set([...ll,"minimum_runtime_version","revision"]),uk=new Set([...ov,"operation"]),fk=512*1024,sv=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),dk=new Set([...sv,"implementationScopeHash","repairScopeHash","repairStagnation"]);var hl=De.maxSpecs*4;async function cv(t,e){let i=dl.join(H(t,e),"specs"),n;try{n=await ma({root:t.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await fl.opendir(i);try{for await(let s of o){if(a+=1,a>hl)throw new Error(`Native proposed specs directory exceeds ${hl} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Wt(s.name);let c=dl.join(i,s.name,"spec.md");await j(t.nativeRoot,c);let l;try{l=await fl.lstat(c)}catch(d){if(d.code==="ENOENT")continue;throw d}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>De.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function vl(t,e){let i=H(t,e),n={},r=0;for(let a of await cv(t,e)){let o=await Y({root:i,ref:`specs/${a}/spec.md`,maxBytes:De.maxFileBytes});if(r+=o.size,r>De.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");n[a]=o.text}return n}import Rv from"path";var lv=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});var gl="scoped-text-safety",uv=1,fv=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var dv="comet.native.checker-policy.v1";var aE=ee(dv,{policy:gl,version:uv,limits:fv,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var hv=["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"],oE=new Set(hv);var pv=nl,EE=3*pv;import{execFile as Nv,spawn as UE}from"node:child_process";import{promisify as bv}from"node:util";var qE=512*1024;var lC=64*1024;var uC=3600*1e3;var fC=bv(Nv);var dC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_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 gn=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var QC={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var lR=16*1024*1024,uR=256*1024,fR=16*1024;var pR=16*1024;var CR=16*1024;var dP=16*1024*1024,wn=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},yn=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var wl=10*1024*1024,ke=class extends Error{};function yl(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ke(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Nl(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ke(`${e} may only be provided once`);if(i.length===0)return;let n=i[0],r=t[n+1];if(r===void 0||r.startsWith("--"))throw new ke(`${e} requires a value`);return t.splice(n,2),r}function bl(t){if(t.length>0)throw new ke(`Unexpected argument: ${t[0]}`)}function Sl(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new ke(`${e} is required`);return i}async function kl(t){return t?Rv.resolve(t):on(process.cwd())}async function El(t){let e=await $c({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function Ta(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
142
+ `,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Vi(e),n=Xe(i);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Vi(e),n=Xe(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};vc.Parser=Xr});var bc=w(Ot=>{"use strict";var gc=Mr(),zh=Et(),_t=Pt(),Wh=Hn(),Jh=C(),Kh=Yr(),wc=Qr();function yc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Kh.LineCounter||null,prettyErrors:e}}function Gh(t,e={}){let{lineCounter:i,prettyErrors:n}=yc(e),r=new wc.Parser(i?.addNewLine),a=new gc.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(_t.prettifyError(t,i)),s.warnings.forEach(_t.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Nc(t,e={}){let{lineCounter:i,prettyErrors:n}=yc(e),r=new wc.Parser(i?.addNewLine),a=new gc.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new _t.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(_t.prettifyError(t,i)),o.warnings.forEach(_t.prettifyError(t,i))),o}function Uh(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=Nc(t,i);if(!r)return null;if(r.warnings.forEach(a=>Wh.warn(r.options.logLevel,a)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},i))}function Yh(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Jh.isDocument(t)&&!n?t.toString(i):new zh.Document(t,n,i).toString(i)}Ot.parse=Uh;Ot.parseAllDocuments=Gh;Ot.parseDocument=Nc;Ot.stringify=Yh});var ea=w(P=>{"use strict";var Xh=Mr(),Qh=Et(),Zh=wr(),Zr=Pt(),ep=ct(),ge=C(),tp=de(),ip=T(),np=pe(),rp=me(),ap=Bi(),op=Gr(),sp=Yr(),cp=Qr(),Wi=bc(),Sc=rt();P.Composer=Xh.Composer;P.Document=Qh.Document;P.Schema=Zh.Schema;P.YAMLError=Zr.YAMLError;P.YAMLParseError=Zr.YAMLParseError;P.YAMLWarning=Zr.YAMLWarning;P.Alias=ep.Alias;P.isAlias=ge.isAlias;P.isCollection=ge.isCollection;P.isDocument=ge.isDocument;P.isMap=ge.isMap;P.isNode=ge.isNode;P.isPair=ge.isPair;P.isScalar=ge.isScalar;P.isSeq=ge.isSeq;P.Pair=tp.Pair;P.Scalar=ip.Scalar;P.YAMLMap=np.YAMLMap;P.YAMLSeq=rp.YAMLSeq;P.CST=ap;P.Lexer=op.Lexer;P.LineCounter=sp.LineCounter;P.Parser=cp.Parser;P.parse=Wi.parse;P.parseAllDocuments=Wi.parseAllDocuments;P.parseDocument=Wi.parseDocument;P.stringify=Wi.stringify;P.visit=Sc.visit;P.visitAsync=Sc.visitAsync});var ba=Oa(ea(),1);import{promises as jm}from"fs";import Le from"path";import{createHash as dp}from"node:crypto";import{promises as U}from"node:fs";import V from"node:path";import{TextDecoder as hp}from"node:util";var lp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),up=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function fp(t){return t.toLowerCase().startsWith(".env")}function jt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>fp(n))?"environment-file":i.some(n=>up.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>lp.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function we(t){return t!==0&&t!==0n&&t!=="0"}function G(t,e){return we(t.dev)&&we(e.dev)&&we(t.ino)&&we(e.ino)}function I(t,e){let i=we(t.dev)&&we(e.dev);if(i&&t.dev!==e.dev)return!1;let n=we(t.ino)&&we(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Ki=1024*1024;function ta(t,e){let i=V.relative(t,e);return i===""||!V.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${V.sep}`)}function pp(t){let e=V.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||V.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=jt(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function mp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function vp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ji(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return G(i,n)?I(i,n):I(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function kc(t){let e=await U.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await U.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function gp(t,e){let i=V.resolve(t),n=V.resolve(e);if(!ta(i,n))throw new Error("Native artifact path is outside its root");let r=[await kc(i)],a=i;for(let o of V.relative(i,n).split(V.sep).filter(Boolean)){a=V.join(a,o);let s=await kc(a);if(!ta(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Ec(t){for(let e of t){let i=await U.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!vp(e,i)||await U.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Y(t){let e=pp(t.ref),i=mp(t.maxBytes??Ki),n=V.resolve(t.root,...e.split("/")),r=await gp(t.root,V.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await U.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await U.realpath(n);if(!ta(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await U.open(n,"r");try{let[c,l,d]=await Promise.all([s.stat(),U.lstat(n),U.realpath(n)]);if(await Ec(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||d!==o||!Ji(a,c)||!Ji(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let u=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let S=i+1-f,k=await s.read(m,0,Math.min(m.length,S),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);u.push(Buffer.from(m.subarray(0,k.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([s.stat(),U.lstat(n),U.realpath(n)]);if(await Ec(r),!h.isFile()||h.isSymbolicLink()||p!==o||!Ji(c,g)||!Ji(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(u,f),N;try{N=new hp("utf-8",{fatal:!0}).decode(y)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:S})}return{ref:e,size:f,hash:dp("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var na=Oa(ea(),1);import Gi from"path";var Xi=64*1024,Ui=1024,Yi=64,ra=5,wp=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],F={include:["**/*"],exclude:[...wp],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function yp(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Gi.posix.isAbsolute(i)||Gi.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function Te(t){let e=yp(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Rc(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function aa(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Gi.posix.isAbsolute(n)||Gi.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function $t(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Pc(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Qi(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ui)throw new Error(`${e} exceeds ${Ui} characters`);let i=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?i+=1:t[n]==="*"&&(i+=1,t[n+1]==="*"&&(n+=1));if(i>Yi)throw new Error(`${e} contains more than ${Yi} wildcard tokens`);return t}function Cc(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>Qi(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function ia(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function Np(t){if(t===void 0)return{...F,include:[...F.include],exclude:[...F.exclude]};let e=$t(t,"native.snapshot");return{include:Cc(e.include,"native.snapshot.include",F.include),exclude:Cc(e.exclude,"native.snapshot.exclude",F.exclude),max_files:ia(e.max_files,F.max_files,"native.snapshot.max_files"),max_total_bytes:ia(e.max_total_bytes,F.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ia(e.max_duration_ms,F.max_duration_ms,"native.snapshot.max_duration_ms")}}function bp(t){if(t===void 0)return;let e=$t(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=$t(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,d=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 d!="string"||!/^[a-f0-9]{64}$/u.test(d))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:d}}return{id:i,fromArtifactRoot:Te(n),toArtifactRoot:Te(r),stage:a,...o?{cleanup:o}:{}}}function Sp(t,e={}){let i=$t(t,"native"),n=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??ra;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=bp(i.pending_root_move);return{artifact_root:Te(n),language:Pc(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:Np(i.snapshot),...s?{pending_root_move:s}:{}}}function kp(t){let e=$t(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Rc(e.artifact_layout),language:Pc(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Ep(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Cp(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function Zi(t,e={}){let i=(0,na.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=Ep(r.ambient_resume),o=r.native===void 0?void 0:Sp(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:kp(r.classic),c=Cp(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function oa(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Te(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:ra,snapshot:{...F,include:[...F.include],exclude:[...F.exclude]}}}}import{createHash as Pp}from"crypto";import{promises as nn}from"fs";import ye from"path";import{constants as en,promises as Ie}from"fs";var ne=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function sa(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Ac(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Ht(t){return{dev:t.dev,ino:t.ino,birthtime:sa(t)}}function tn(t,e){let i=Ht(t),n=Ht(e);return G(i,n)?I(i,n):I(i,n)&&sa(t)===sa(e)&&Ac(t)===Ac(e)&&t.size===e.size}async function Lt(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Ie.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new ne("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ne("too-large",`${n} exceeds ${e} bytes`);let o=await Ie.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Ht(a)});let s=process.platform==="win32"?en.O_RDONLY:en.O_RDONLY|en.O_NOFOLLOW|en.O_NONBLOCK,c;try{c=await Ie.open(t,s)}catch(l){throw l.code==="ELOOP"?new ne("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!tn(a,l)||!tn(a,d))throw new ne("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Ht(l)}),await i.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-m,{bytesRead:S}=await c.read(g,0,Math.min(g.length,N),null);if(S===0)break;if(m+=S,m>e)throw new ne("too-large",`${n} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[h,p,y]=await Promise.all([c.stat({bigint:r}),Ie.lstat(t,{bigint:r}),Ie.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!tn(a,h)||!tn(a,p))throw new ne("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Ht(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:y}}finally{await c.close()}}function Rp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ca(t,e){let i=ye.relative(t,e);return i===""||!ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ye.sep}`)}async function xc(t,e){let i=ye.resolve(t),n=await nn.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return nn.realpath(i)}async function Tc(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=ye.join(r,i[a]);let o;try{o=await nn.lstat(r)}catch(d){if(Rp(d))return{exists:!1,kind:"missing"};throw d}let s=ye.relative(t,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await nn.realpath(r);if(!ca(e,l))throw new Error(`${n.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 Mt(t,e,i){let n=aa(e,i.label),r=ye.resolve(t),a=await xc(r,i.label),o=n.split("/"),s=ye.resolve(r,...o);if(!ca(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Tc(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Qe(t,e,i,n){let r=await Mt(t,e,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await xc(r.projectRoot,n.label);return Lt(r.target,i,{...n,verify:async(o,s)=>{if(!ca(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Tc(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var Dt=".comet/config.yaml";function Ap(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function la(t,e={}){return(await rn(t,e)).document}async function xp(t){try{return(await Qe(t,Dt,Xi,{label:Dt})).bytes}catch(e){if(Ap(e))return null;throw e}}function Tp(t){return t?{exists:!0,sha256:Pp("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function rn(t,e={}){let i=await xp(t);return{document:i?Zi(i.toString("utf8"),e):null,identity:Tp(i)}}var Rw=16*1024;import{promises as Ze}from"fs";import A from"path";import $p from"os";var an=".comet/config.yaml";async function fa(t){try{return await Ze.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Hp(t){try{let e=await Ze.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Ft(t,e){let i=A.relative(t,e);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function Bt(t){let e=[],i=t;for(;!await fa(i);){let r=A.dirname(i);if(r===i)break;e.push(A.basename(i)),i=r}let n=await Ze.realpath(i);return A.resolve(n,...e.reverse())}async function jc(t){try{return(await Ze.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function on(t){let e=A.resolve(t);try{(await Ze.stat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=A.resolve($p.homedir());for(;;){if(!(e===n&&i!==n)){let o=A.join(e,...an.split("/")),s=e===i||await Hp(o);if(await fa(o)&&s)return e}if(await fa(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return i;e=a}}function sn(t){return Te(t)}async function Lp(t,e){let i=sn(e),n=A.resolve(t,...i.split("/")),r=await Ze.realpath(t),a=await Bt(n);if(!Ft(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function da(t,e){let i=sn(e),n=await Lp(t,i),r=A.join(n,"comet");if(await jc(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Bt(n),Bt(r)]);if(!Ft(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:A.resolve(t),configFile:A.join(t,...an.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:A.join(r,"specs"),changesDir:A.join(r,"changes"),archiveDir:A.join(r,"archive"),runtimeDir:A.join(r,"runtime"),locksDir:A.join(r,"runtime","locks"),transactionsDir:A.join(r,"runtime","transactions")}}function re(t,e){return Ft(A.resolve(t),A.resolve(e))}async function j(t,e){let i=A.resolve(t),n=A.resolve(e);if(!Ft(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await jc(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([Bt(i),Bt(n)]);if(!Ft(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var cn=Qi;function Dp(t="docs",e="en"){return oa(t,e)}async function qt(t){let e=(await la(t))?.config??null;return e?.native?e:null}async function $c(t){let e=await on(t.startPath),i=await qt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${an} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=t.explicitArtifactRoot?sn(t.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??Dp(n??"docs"),a=await da(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{AsyncLocalStorage as Fp}from"async_hooks";var Yw=16*1024;var Xw=new Fp;import{TextDecoder as Gp}from"util";import{createHash as Bp}from"node:crypto";import{constants as ln,promises as X}from"node:fs";import Q from"node:path";import{TextDecoder as qp}from"node:util";function fn(t,e){let i=Q.relative(t,e);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function Vp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function zp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Wp(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function un(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function pa(t,e){let i=await X.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await X.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Hc(t,e,i){let n=Q.resolve(t),r=Q.resolve(e);if(!fn(n,r))throw new Error(`${i} is outside its managed root`);let a=[await pa(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await Ne(a,i),o=Q.join(o,s);let c=await pa(o,i);if(!fn(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ne(a,i),a}async function Ne(t,e){for(let i of t){let n=await X.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!zp(i,n)||await X.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function Jp(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function et(t){let e=Vp(t.maxBytes),i=Q.resolve(t.file),n=await Hc(t.root,Q.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(d=>pa(Q.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ne(n,t.label);let a=await X.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Wp(a),s=await X.realpath(i);if(!fn(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(d=>fn(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ln.O_RDONLY:ln.O_RDONLY|ln.O_NOFOLLOW|ln.O_NONBLOCK,l=await X.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([X.lstat(i),X.realpath(i)]);if(await Ne(n,t.label),await Ne(r,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!un(o,d)||!un(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await Jp(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([l.stat(),X.lstat(i),X.realpath(i)]);if(await Ne(n,t.label),await Ne(r,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!un(o,g)||!un(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:Bp("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function Lc(t){let e=await et(t),i;try{i=new qp("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}async function ma(t){let e=await Hc(t.root,t.directory,t.label);return{verify:()=>Ne(e,t.label)}}var hy=256*1024,py=1024*1024,my=16*1024;var vy=64*1024*1024;var gy=new Gp("utf-8",{fatal:!0});import hn from"path";import{createHash as Yp}from"crypto";function B(t){return Yp("sha256").update(t).digest("hex")}var $y={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Qp=1e3,Zp=8*1024*1024,em=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tm=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),im=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),nm=new Set(["schema","include","exclude","hash"]),rm=new Set(["provider","gitSelection","physicalSelection","projection"]),am=new Set(["provider","selection"]),om=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),sm=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),cm=new Set(["schema","status","before","after"]),lm=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),um=new Set(["path","hash","size","type","gitObjectId"]),fm=new Set(["path","size","type","reason"]),dm=new Set(["ref","hash","count"]),hm=new Set(["change-created","legacy-migration","explicit"]),pm=new Set(["file","directory","other"]),mm=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"]),pn=/^[a-f0-9]{64}$/u,vm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var Hy=64*1024,Ly=64*1024;var My={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Dy={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function dn(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var Fy=(1n<<256n)-1n;function gm(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function wm(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
143
+ `)}function ym(t,e){return B(`comet.native.snapshot-policy.v1
144
+ ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function ga(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function Nm(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function qc(t){let e=cn(t,"Native snapshot pattern"),i=[];for(let n=0;n<e.length;n+=1){let r=e[n];r==="*"&&e[n+1]==="*"?(n+=1,e[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?Nm(r):void 0;if(a&&!a())return!1;let o=ga(i,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let d=i[l];d&&(d.kind==="literal"&&d.value===s||d.kind==="question"&&s!=="/"?c.add(l+1):d.kind==="star"&&s!=="/"||d.kind==="globstar"?c.add(l):d.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=ga(i,c,a),o===null||o.size===0)return!1}return ga(i,o,a)?.has(i.length)??!1}}function bm(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>cn(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>cn(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=ym(e,i);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:n},includeMatchers:e.map(qc),excludeMatchers:i.map(qc),excludedDirectoryPrefixes:i.flatMap(r=>{if(!r.endsWith("/**"))return[];let a=r.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((r,a)=>r.localeCompare(a,"en"))}}function z(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function W(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function it(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ae(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Wc(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=hn.posix.normalize(t);if(i!==t||hn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function Sm(t,e){let i=z(t,`Native snapshot entry ${e}`);W(i,um,`Native snapshot entry ${e}`);let n=Wc(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:ae(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!vm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function km(t,e){let i=z(t,`Native snapshot omission ${e}`);if(W(i,fm,`Native snapshot omission ${e}`),!pm.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!mm.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Wc(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:ae(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function Em(t){let e=z(t,"Native snapshot omission overflow");if(W(e,dm,"Native snapshot omission overflow"),typeof e.hash!="string"||!pn.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:it(e.count,"Native snapshot omission overflow count")}}function tt(t,e){let i=z(t,e);if(W(i,sm,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=ae(i.recordCount,`${e} recordCount`),r=ae(i.storedRecordCount,`${e} storedRecordCount`),a=ae(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function Vc(t){let e=z(t,"Native Git selection evidence");if(W(e,om,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=tt(e.stageBefore,"Native Git selection stageBefore"),n=tt(e.combined,"Native Git selection combined"),r=tt(e.stageAfter,"Native Git selection stageAfter"),a=tt(e.finalStageBefore,"Native Git selection finalStageBefore"),o=tt(e.finalCombined,"Native Git selection finalCombined"),s=tt(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!dn(i,r)||!dn(r,a)||!dn(n,o)||!dn(a,s),d=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==d)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:d,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function zc(t,e){let i=z(t,e);if(W(i,lm,e),typeof i.hash!="string"||!pn.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=ae(i.visitedNodeCount,`${e} visitedNodeCount`),r=ae(i.recordCount,`${e} recordCount`),a=ae(i.storedRecordCount,`${e} storedRecordCount`),o=ae(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Cm(t){let e=z(t,"Native physical selection evidence");if(W(e,cm,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=zc(e.before,"Native physical selection before"),n=zc(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!gm(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function Jc(t){let e=z(t,"Native content snapshot manifest");if(W(e,tm,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!hm.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=z(e.capture,"Native content snapshot capture");if(W(v,rm,"Native content snapshot capture"),v.provider!=="git"&&v.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=v.gitSelection===void 0?void 0:Vc(v.gitSelection),b=v.physicalSelection===void 0?void 0:Cm(v.physicalSelection),x=null;if(v.projection!==void 0){let D=z(v.projection,"Native content snapshot projection");if(W(D,am,"Native content snapshot projection"),D.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");x={provider:"git",...D.selection===void 0?{}:{selection:Vc(D.selection)}}}if(v.provider==="git"){if(b||x)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&x)throw new Error("Native physical-tree capture cannot combine selection and projection");i=x?{provider:"physical-tree",projection:x}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=z(e.limits,"Native content snapshot limits");W(n,im,"Native content snapshot limits");let r={maxFiles:it(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:it(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:it(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:it(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:it(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=z(e.policy,"Native snapshot policy");if(W(v,nm,"Native snapshot policy"),v.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(v.include)||!Array.isArray(v.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=bm({include:v.include,exclude:v.exclude,hash:v.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(Sm),s=e.omitted.map(km),c=ae(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Em(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(v=>v.size>r.maxFileBytes)||o.reduce((v,R)=>v+R.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(v=>v.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Qp||c<s.length)throw new Error("Native content snapshot omission count is invalid");let d=c-s.length;if(d===0&&l||d>0&&l?.count!==d)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let u=s.filter(v=>v.reason==="git-enumeration-limit"),f=s.filter(v=>v.reason==="git-selection-changed");for(let v of[...u,...f])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(u.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let m=i?.provider==="git"?i.gitSelection:i?.projection?.selection,g=m?.status==="overflow"||m?.status==="overflow-and-changed",h=m?.status==="changed"||m?.status==="overflow-and-changed";if(g!==(u.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 p=s.filter(v=>v.reason==="physical-enumeration-limit"),y=s.filter(v=>v.reason==="physical-selection-changed");for(let v of[...p,...y])if(v.path!=="."||v.size!==null||v.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=i?.physicalSelection,S=N?.status==="overflow"||N?.status==="overflow-and-changed",k=N?.status==="changed"||N?.status==="overflow-and-changed";if(S!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(wm(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Rm(t,e){if(!em.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=hn.join(t.changesDir,e);if(!re(t.changesDir,i))throw new Error("Native change path escaped");return hn.join(i,"runtime","baseline-manifest.json")}async function Kc(t,e){let i=Rm(t,e);await j(t.nativeRoot,i);try{let n=await Lc({root:t.nativeRoot,file:i,maxBytes:Zp,label:"Native baseline snapshot manifest"});return Jc(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var _N=256*1024;var WN={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};var nb=16*1024;var je="comet.native.v3",$e="comet.native.v2",He="comet.native.v1";var Uc=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],$m=new Set(Uc),Yc=new Set([...Uc,"minimum_runtime_version","revision"]),Hm=new Set([...Yc,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Lm=new Set(["capability","operation","source","base_hash"]),Mm=new Set(["shape","build","verify","archive"]),Dm=new Set(["implicit","confirmed"]),Fm=new Set(["pending","pass","fail"]),Me="comet-state.yaml",ya=/^[a-f0-9]{64}$/u,Xc=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Bm=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Na=class extends Error{constructor(i,n){super(`Native change ${i} uses ${n}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Se=class extends Error{constructor(i,n){super(i!==je||n===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},mn=class extends Error{constructor(i,n,r){super(`Native change ${i} revision conflict: expected ${n}, actual ${r}`);this.change=i;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},vn=class extends Error{constructor(i,n,r,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=n;this.omittedByReason=r;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"},Eb=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
145
+ `);function zt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Qc(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Wt(t){if(!Xc.test(t))throw new Error(`Invalid Native change name: ${t}`)}function qm(t){if(!Xc.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Zc(t,e){if(t.length===0||Le.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Vm(t,e){let i=zt(t,`spec_changes[${e}]`);if(Qc(i,Lm,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(qm(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let n=i.source,r=i.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof n=="string"&&Zc(n,`Spec source for ${i.capability}`),i.operation==="create"){if(!n)throw new Error(`Create spec ${i.capability} requires source`);if(r!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!n)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof r!="string"||!ya.test(r))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof r!="string"||!ya.test(r))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof n=="string"?{source:n}:{},base_hash:r}}function zm(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Sa(t,e){if(Qc(t,e,Me),typeof t.name!="string")throw new Error("Native change name is required");if(Wt(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!Mm.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!Dm.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(Vm),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!Fm.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&Zc(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!zm(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ka(t){let e=zt(t,Me);if(e.schema!==He)throw new Error(`Expected ${He}`);return{schema:He,...Sa(e,$m)}}function Vt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function wa(t,e,i){if(t===null)return null;let n=typeof t=="string"?Bm.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function Wm(t){if(t==null)return null;if(typeof t!="string"||!ya.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function Jm(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Ea(t){let e=zt(t,Me);if(e.schema!==$e)throw new Error(`Expected ${$e}`);if(Vt(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${$e} minimum_runtime_version must be 2`);return{schema:$e,minimum_runtime_version:2,revision:Vt(e.revision,"Native v2 revision"),...Sa(e,Yc)}}function Ca(t){let e=zt(t,Me);if(e.schema!==je){if(e.schema===He||e.schema===$e){let o=e.schema===He?ka(e):Ea(e);throw new Na(o.name,o.schema)}throw new Se(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Vt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Se(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Vt(e.revision,"Native revision"),r=Sa(e,Hm),a=Wm(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:je,minimum_runtime_version:3,revision:n,verification_protocol:Jm(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:wa(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:wa(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:wa(e.partial_allowance,"Native partial_allowance","allowances")}}function Km(t){let e=zt(t,Me);if(e.schema===He){let r=ka(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${je}`}}if(e.schema===$e){let r=Ea(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${je}`}}if(e.schema!==je){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Se(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Vt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Se(e.schema,i).message};let n=Ca(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function H(t,e){Wt(e);let i=Le.join(t.changesDir,e);if(!re(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Ra(t,e){let i=Le.join(H(t,e),"runtime","schema-migration.json");await j(t.nativeRoot,i);try{return await jm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var Gm=256*1024;async function Um(t,e=Le.dirname(t)){let i=Le.relative(e,t).split(Le.sep).join("/"),n=await Y({root:e,ref:i,maxBytes:Gm}),r=(0,ba.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function el(t,e){let i=Le.join(H(t,e),Me);await j(t.nativeRoot,i);let n=Km(await Um(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ra(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await Ym(t,n.state),n)}async function Ym(t,e){if(await Kc(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}import{createHash as Xm}from"crypto";function Z(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Qm(t,e){e.has(t)&&Z("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;n<t.length;n+=1)Object.prototype.hasOwnProperty.call(t,n)||Z("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Z("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Z("symbol properties are not supported"),`[${t.map(n=>Pa(n,e)).join(",")}]`}finally{e.delete(t)}}function Zm(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Z("only plain objects are supported"),e.has(t)&&Z("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Z("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Z("accessor properties are not supported"),`${JSON.stringify(o)}:${Pa(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Pa(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Z("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Qm(t,e):Zm(t,e);case"bigint":case"function":case"symbol":case"undefined":return Z(`${typeof t} values are not supported`)}return Z("unsupported value type")}function Aa(t){return Pa(t,new Set)}function ee(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return Xm("sha256").update(`${t}
146
+ ${Aa(e)}`).digest("hex")}var xb=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),tl=Object.freeze({maxCriteria:1024});var Hb={maxAcceptanceCriteria:tl.maxCriteria};var De={maxSpecs:64,maxFileBytes:Ki,maxTotalBytes:4*1024*1024};import{promises as fl}from"fs";import dl from"path";var ev=["Outcome","Scope","Non-goals","Acceptance examples"],Jb=[...ev,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var nS={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var nl=1024*1024;var al={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:[]},iv=B("comet-native-runtime:v3:semantic-repair-budget"),IS=[{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];var ll=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],uk=new Set(ll),sv=new Set([...ll,"minimum_runtime_version","revision"]),fk=new Set([...sv,"operation"]),dk=512*1024,cv=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),hk=new Set([...cv,"implementationScopeHash","repairScopeHash","repairStagnation"]);var hl=De.maxSpecs*4;async function lv(t,e){let i=dl.join(H(t,e),"specs"),n;try{n=await ma({root:t.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await fl.opendir(i);try{for await(let s of o){if(a+=1,a>hl)throw new Error(`Native proposed specs directory exceeds ${hl} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Wt(s.name);let c=dl.join(i,s.name,"spec.md");await j(t.nativeRoot,c);let l;try{l=await fl.lstat(c)}catch(d){if(d.code==="ENOENT")continue;throw d}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>De.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function vl(t,e){let i=H(t,e),n={},r=0;for(let a of await lv(t,e)){let o=await Y({root:i,ref:`specs/${a}/spec.md`,maxBytes:De.maxFileBytes});if(r+=o.size,r>De.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");n[a]=o.text}return n}import Pv from"path";var uv=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});var gl="scoped-text-safety",fv=1,dv=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var hv="comet.native.checker-policy.v1";var oE=ee(hv,{policy:gl,version:fv,limits:dv,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var pv=["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"],sE=new Set(pv);var mv=nl,CE=3*mv;import{execFile as bv,spawn as YE}from"node:child_process";import{promisify as Sv}from"node:util";var VE=512*1024;var uC=64*1024;var fC=3600*1e3;var dC=Sv(bv);var hC=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_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 gn=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var ZC={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var uR=16*1024*1024,fR=256*1024,dR=16*1024;var mR=16*1024;var RR=16*1024;var hP=16*1024*1024,wn=class extends Error{constructor(i,n,r,a){super(`Canonical spec conflict for ${i}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=i;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},yn=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var wl=10*1024*1024,ke=class extends Error{};function yl(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ke(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Nl(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ke(`${e} may only be provided once`);if(i.length===0)return;let n=i[0],r=t[n+1];if(r===void 0||r.startsWith("--"))throw new ke(`${e} requires a value`);return t.splice(n,2),r}function bl(t){if(t.length>0)throw new ke(`Unexpected argument: ${t[0]}`)}function Sl(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new ke(`${e} is required`);return i}async function kl(t){return t?Pv.resolve(t):on(process.cwd())}async function El(t){let e=await $c({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function Ta(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
147
147
  `}}function Cl(t,e){if(e instanceof ke)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof wn)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof yn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof mn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof vn)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof gn)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Rl(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
148
- `}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Pl(t,e){let i=Sl(t,"change name");bl(t);let{paths:n}=await El(e),r=await el(n,i);if(r.status==="migration-required")return Ta("show",{name:i,schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,migrationRequired:!0,message:r.message});if(r.status!=="current"||!r.state)throw new Se(r.schema,r.minimumRuntimeVersion);let a=r.state,o=H(n,i),s=await vl(n,i),c=await Y({root:o,ref:a.brief,maxBytes:De.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>wl)throw new Error("Native show output exceeds its serialized byte budget");return Ta("show",l)}function Pv(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
149
- `}}async function Al(t,e,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{yl(r,"--json"),s=Nl(r,"--project-root");let d=[...r,...a],u=await kl(s);c=await e(d,u)}catch(d){c=Cl(t,d)}let l=o?Pv(c):Rl(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
148
+ `}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Pl(t,e){let i=Sl(t,"change name");bl(t);let{paths:n}=await El(e),r=await el(n,i);if(r.status==="migration-required")return Ta("show",{name:i,schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,migrationRequired:!0,message:r.message});if(r.status!=="current"||!r.state)throw new Se(r.schema,r.minimumRuntimeVersion);let a=r.state,o=H(n,i),s=await vl(n,i),c=await Y({root:o,ref:a.brief,maxBytes:De.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>wl)throw new Error("Native show output exceeds its serialized byte budget");return Ta("show",l)}function Av(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
149
+ `}}async function Al(t,e,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{yl(r,"--json"),s=Nl(r,"--project-root");let d=[...r,...a],u=await kl(s);c=await e(d,u)}catch(d){c=Cl(t,d)}let l=o?Av(c):Rl(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
150
150
  `)?"":`
151
151
  `)),l.exitCode}process.exitCode=await Al("show",Pl);