@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 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
139
139
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
140
140
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.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 t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){ui(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&t.sep&&!t.value){let o=[];for(let s=0;s<t.sep.length;++s){let c=t.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=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.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(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(oe(t.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(as(t.key)&&!oe(t.sep,"newline")){let o=xe(t.start),s=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken);else if(oe(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=xe(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):oe(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{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||t.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!oe(t.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 t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.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 t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){ui(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||oe(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.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 t=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":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{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=li(n),a=xe(r);rs(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 t=this.source.indexOf(`
141
141
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
142
- `,t)+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 t=li(e),n=xe(t);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 t=li(e),n=xe(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!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())}}};os.Parser=nr});var fs=v(st=>{"use strict";var ss=zn(),Sd=Qe(),ot=tt(),kd=Bi(),Ed=C(),Cd=ir(),cs=rr();function ls(i){let e=i.prettyErrors!==!1;return{lineCounter:i.lineCounter||e&&new Cd.LineCounter||null,prettyErrors:e}}function Rd(i,e={}){let{lineCounter:t,prettyErrors:n}=ls(e),r=new cs.Parser(t?.addNewLine),a=new ss.Composer(e),o=Array.from(a.compose(r.parse(i)));if(n&&t)for(let s of o)s.errors.forEach(ot.prettifyError(i,t)),s.warnings.forEach(ot.prettifyError(i,t));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function us(i,e={}){let{lineCounter:t,prettyErrors:n}=ls(e),r=new cs.Parser(t?.addNewLine),a=new ss.Composer(e),o=null;for(let s of a.compose(r.parse(i),!0,i.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new ot.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ot.prettifyError(i,t)),o.warnings.forEach(ot.prettifyError(i,t))),o}function Pd(i,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=us(i,t);if(!r)return null;if(r.warnings.forEach(a=>kd.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},t))}function Ad(i,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(i===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return Ed.isDocument(i)&&!n?i.toString(t):new Sd.Document(i,n,t).toString(t)}st.parse=Pd;st.parseAllDocuments=Rd;st.parseDocument=us;st.stringify=Ad});var or=v(R=>{"use strict";var xd=zn(),Td=Qe(),Id=En(),ar=tt(),_d=He(),se=C(),Od=ie(),jd=A(),$d=re(),Hd=ae(),Ld=si(),Md=er(),Dd=ir(),Fd=rr(),fi=fs(),ds=_e();R.Composer=xd.Composer;R.Document=Td.Document;R.Schema=Id.Schema;R.YAMLError=ar.YAMLError;R.YAMLParseError=ar.YAMLParseError;R.YAMLWarning=ar.YAMLWarning;R.Alias=_d.Alias;R.isAlias=se.isAlias;R.isCollection=se.isCollection;R.isDocument=se.isDocument;R.isMap=se.isMap;R.isNode=se.isNode;R.isPair=se.isPair;R.isScalar=se.isScalar;R.isSeq=se.isSeq;R.Pair=Od.Pair;R.Scalar=jd.Scalar;R.YAMLMap=$d.YAMLMap;R.YAMLSeq=Hd.YAMLSeq;R.CST=Ld;R.Lexer=Md.Lexer;R.LineCounter=Dd.LineCounter;R.Parser=Fd.Parser;R.parse=fi.parse;R.parseAllDocuments=fi.parseAllDocuments;R.parseDocument=fi.parseDocument;R.stringify=fi.stringify;R.visit=ds.visit;R.visitAsync=ds.visitAsync});import Xh from"path";import br from"node:path";import{createHash as ec}from"crypto";function M(i){throw new TypeError(`Value is not valid canonical JSON: ${i}`)}function tc(i,e){e.has(i)&&M("cyclic structures are not supported"),e.add(i);try{let t=Object.keys(i);for(let n=0;n<i.length;n+=1)Object.prototype.hasOwnProperty.call(i,n)||M("sparse arrays are not supported");return(t.length!==i.length||t.some((n,r)=>n!==String(r)))&&M("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(i).length>0&&M("symbol properties are not supported"),`[${i.map(n=>ki(n,e)).join(",")}]`}finally{e.delete(i)}}function ic(i,e){let t=Object.getPrototypeOf(i);t!==Object.prototype&&t!==null&&M("only plain objects are supported"),e.has(i)&&M("cyclic structures are not supported"),Object.getOwnPropertySymbols(i).length>0&&M("symbol properties are not supported"),e.add(i);try{let n=Object.getOwnPropertyDescriptors(i);return`{${Object.keys(i).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&M("accessor properties are not supported"),`${JSON.stringify(o)}:${ki(s.value,e)}`}).join(",")}}`}finally{e.delete(i)}}function ki(i,e){if(i===null)return"null";switch(typeof i){case"boolean":return i?"true":"false";case"string":return JSON.stringify(i);case"number":return Number.isFinite(i)||M("numbers must be finite"),JSON.stringify(Object.is(i,-0)?0:i);case"object":return Array.isArray(i)?tc(i,e):ic(i,e);case"bigint":case"function":case"symbol":case"undefined":return M(`${typeof i} values are not supported`)}return M("unsupported value type")}function Ei(i){return ki(i,new Set)}function D(i,e){if(i.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(i))throw new TypeError("Canonical hash tag must not contain a line break");return ec("sha256").update(`${i}
143
- ${Ei(e)}`).digest("hex")}var nc=/^acceptance-[a-f0-9]{64}$/u,rc=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),ac=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var rp=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Sr=Object.freeze({maxCriteria:1024}),oc="<!-- comet-native:acceptance-evidence:start -->",sc="<!-- comet-native:acceptance-evidence:end -->";function cc(i){return Array.from(i).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127})}function lc(i,e){let t=i.trim().replaceAll("\\","/");if(t.length===0||cc(t)||br.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(t)||t.split("/").includes(".."))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);let n=br.posix.normalize(t);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${e} references sensitive content`);if(!ac.test(n))throw new Error(`Acceptance evidence ${e} must reference a content-addressed typed receipt`);return n}function uc(i,e){if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`Acceptance evidence entry ${e} must be an object`);let t=i,n=Object.keys(t).filter(r=>!rc.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${e} has unknown field(s): ${n.join(", ")}`);return t}function fc(i){if(!Array.isArray(i))throw new Error("Native acceptance evidence block must be a JSON array");let e=new Set;return i.map((t,n)=>{let r=uc(t,n),a=r.acceptance_id;if(typeof a!="string"||!nc.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(e.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(e.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return lc(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function dc(i){let e=fc([...i]).map(t=>({...t,evidence_refs:[...t.evidence_refs].sort()})).sort((t,n)=>t.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(e,null,2)}function kr(i){return[oc,dc(i),sc].join(`
144
- `)}function X(i){return i!==0&&i!==0n&&i!=="0"}function W(i,e){return X(i.dev)&&X(e.dev)&&X(i.ino)&&X(e.ino)}function O(i,e){let t=X(i.dev)&&X(e.dev);if(t&&i.dev!==e.dev)return!1;let n=X(i.ino)&&X(e.ino);return n&&i.ino!==e.ino?!1:t&&n?!0:i.birthtime===e.birthtime}var hs=Nr(or(),1),sr=64*1024;var Bd=[".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/**"],ps={include:["**/*"],exclude:[...Bd],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};import{constants as di,promises as me}from"fs";var q=class extends Error{reason;constructor(e,t,n){super(t,n),this.name="RaceSafeReadError",this.reason=e}};function cr(i){return"birthtimeNs"in i&&typeof i.birthtimeNs=="bigint"?i.birthtimeNs:i.birthtimeMs}function ms(i){return"ctimeNs"in i&&typeof i.ctimeNs=="bigint"?i.ctimeNs:i.ctimeMs}function ct(i){return{dev:i.dev,ino:i.ino,birthtime:cr(i)}}function hi(i,e){let t=ct(i),n=ct(e);return W(t,n)?O(t,n):O(t,n)&&cr(i)===cr(e)&&ms(i)===ms(e)&&i.size===e.size}async function lt(i,e,t={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=t.label??"file",r=t.bigint===!0,a=await me.lstat(i,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new q("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new q("too-large",`${n} exceeds ${e} bytes`);let o=await me.realpath(i);await t.verify?.("pre-open",{realPath:o,identity:ct(a)});let s=process.platform==="win32"?di.O_RDONLY:di.O_RDONLY|di.O_NOFOLLOW|di.O_NONBLOCK,c;try{c=await me.open(i,s)}catch(l){throw l.code==="ELOOP"?new q("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,h,u]=await Promise.all([c.stat({bigint:r}),me.lstat(i,{bigint:r}),me.realpath(i)]);if(!l.isFile()||!h.isFile()||h.isSymbolicLink()||u!==o||!hi(a,l)||!hi(a,h))throw new q("changed",`${n} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:ct(l)}),await t.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-m,{bytesRead:b}=await c.read(g,0,Math.min(g.length,N),null);if(b===0)break;if(m+=b,m>e)throw new q("too-large",`${n} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,b)))}await t.hooks?.beforeFinalCheck?.();let[d,p,w]=await Promise.all([c.stat({bigint:r}),me.lstat(i,{bigint:r}),me.realpath(i)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!hi(a,d)||!hi(a,p))throw new q("changed",`${n} changed while reading`);return await t.verify?.("post-read",{realPath:w,identity:ct(d)}),{bytes:Buffer.concat(f,m),stat:d,realPath:w}}finally{await c.close()}}var zm=16*1024;import{promises as fr}from"fs";import Te from"path";import Kd from"os";var ks=".comet/config.yaml";async function Ss(i){try{return await fr.lstat(i),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Gd(i){try{let e=await fr.readFile(i,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function dr(i){let e=Te.resolve(i);try{(await fr.stat(e)).isDirectory()||(e=Te.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let t=e,n=Te.resolve(Kd.homedir());for(;;){if(!(e===n&&t!==n)){let o=Te.join(e,...ks.split("/")),s=e===t||await Gd(o);if(await Ss(o)&&s)return e}if(await Ss(Te.join(e,".git")))return e;let a=Te.dirname(e);if(a===e)return t;e=a}}import{createHash as ih}from"crypto";function V(i){return ih("sha256").update(i).digest("hex")}var Av={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var xv=8*1024*1024;var Tv=64*1024,Iv=64*1024;var _v={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Ov={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var jv=(1n<<256n)-1n;var ut=1024*1024;import Yh from"path";var xs=Nr(or(),1);var vr=1024*1024;import{AsyncLocalStorage as rh}from"async_hooks";var ig=16*1024;var ng=new rh;import{TextDecoder as oh}from"util";var fg=256*1024,dg=1024*1024,hg=16*1024;var pg=64*1024*1024;var mg=new oh("utf-8",{fatal:!0});var pw=256*1024;var Pw={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 Dw=16*1024;var Ts=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],cy=new Set(Ts),vh=new Set([...Ts,"minimum_runtime_version","revision"]),ly=new Set([...vh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]);var vi=class extends Error{constructor(t,n,r){super(`Native change ${t} revision conflict: expected ${n}, actual ${r}`);this.change=t;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},gi=class extends Error{constructor(t,n,r,a,o,s=null,c=null){super(`Native change ${t} 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=t;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"},uy=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
145
- `);var fy=256*1024;var wh=["Outcome","Scope","Non-goals","Acceptance examples"],gy=[...wh,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var yh=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 _s="scoped-text-safety",Nh=1,bh=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Sh="comet.native.checker-policy.v1";var Ty=D(Sh,{policy:_s,version:Nh,limits:bh,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var kh=["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"],Iy=new Set(kh);var Ch=ut,Uy=3*Ch;var Os={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:[]},Rh=V("comet-native-runtime:v3:semantic-repair-budget"),EN=[{skillVersion:"2",skillHash:V("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:V("comet-native-runtime:v1")}];var $s=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],ob=new Set($s),jh=new Set([...$s,"minimum_runtime_version","revision"]),sb=new Set([...jh,"operation"]),cb=512*1024,$h=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),lb=new Set([...$h,"implementationScopeHash","repairScopeHash","repairStagnation"]);var vb={maxAcceptanceCriteria:Sr.maxCriteria};var bb={maxSpecs:64,maxFileBytes:vr,maxTotalBytes:4*1024*1024};import{execFile as Vh,spawn as sS}from"node:child_process";import{promisify as zh}from"node:util";var _b={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var eS=512*1024;var bS=64*1024;var SS=3600*1e3;var kS=zh(Vh);var ES=["$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 yi=class extends Error{details;constructor(e){let t=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(t),this.name="NativeVerificationReceiptBindingError",this.details=e}};var uk={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var Sk=16*1024*1024,kk=256*1024,Ek=16*1024;var Pk=16*1024;var Dk=16*1024;var PE=16*1024*1024,Ni=class extends Error{constructor(t,n,r,a){super(`Canonical spec conflict for ${t}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=t;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},bi=class extends Error{constructor(t,n=t.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${t.findingCodes.join(", ")}`){super(n);this.preflight=t;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var LE=10*1024*1024,z=class extends Error{};function Ls(i,e){let t=i.flatMap((n,r)=>n===e?[r]:[]);if(t.length>1)throw new z(`${e} may only be provided once`);return t.length===0?!1:(i.splice(t[0],1),!0)}function Si(i,e){let t=i.flatMap((a,o)=>a===e?[o]:[]);if(t.length>1)throw new z(`${e} may only be provided once`);if(t.length===0)return;let n=t[0],r=i[n+1];if(r===void 0||r.startsWith("--"))throw new z(`${e} requires a value`);return i.splice(n,2),r}function Ms(i){if(i.length>0)throw new z(`Unexpected argument: ${i[0]}`)}function Ds(i,e){let t=i.shift();if(!t||t.startsWith("--"))throw new z(`${e} is required`);return t}async function Fs(i){return i?Yh.resolve(i):dr(process.cwd())}function Bs(i,e,t){return{command:i,exitCode:0,data:e,text:t??JSON.stringify(e,null,2)+`
142
+ `,t)+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 t=li(e),n=xe(t);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 t=li(e),n=xe(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!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())}}};os.Parser=nr});var fs=v(st=>{"use strict";var ss=zn(),Sd=Qe(),ot=tt(),kd=Bi(),Ed=C(),Cd=ir(),cs=rr();function ls(i){let e=i.prettyErrors!==!1;return{lineCounter:i.lineCounter||e&&new Cd.LineCounter||null,prettyErrors:e}}function Rd(i,e={}){let{lineCounter:t,prettyErrors:n}=ls(e),r=new cs.Parser(t?.addNewLine),a=new ss.Composer(e),o=Array.from(a.compose(r.parse(i)));if(n&&t)for(let s of o)s.errors.forEach(ot.prettifyError(i,t)),s.warnings.forEach(ot.prettifyError(i,t));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function us(i,e={}){let{lineCounter:t,prettyErrors:n}=ls(e),r=new cs.Parser(t?.addNewLine),a=new ss.Composer(e),o=null;for(let s of a.compose(r.parse(i),!0,i.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new ot.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ot.prettifyError(i,t)),o.warnings.forEach(ot.prettifyError(i,t))),o}function Pd(i,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=us(i,t);if(!r)return null;if(r.warnings.forEach(a=>kd.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},t))}function Ad(i,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(i===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return Ed.isDocument(i)&&!n?i.toString(t):new Sd.Document(i,n,t).toString(t)}st.parse=Pd;st.parseAllDocuments=Rd;st.parseDocument=us;st.stringify=Ad});var or=v(R=>{"use strict";var xd=zn(),Td=Qe(),Id=En(),ar=tt(),_d=He(),se=C(),Od=ie(),jd=A(),$d=re(),Hd=ae(),Ld=si(),Md=er(),Dd=ir(),Fd=rr(),fi=fs(),ds=_e();R.Composer=xd.Composer;R.Document=Td.Document;R.Schema=Id.Schema;R.YAMLError=ar.YAMLError;R.YAMLParseError=ar.YAMLParseError;R.YAMLWarning=ar.YAMLWarning;R.Alias=_d.Alias;R.isAlias=se.isAlias;R.isCollection=se.isCollection;R.isDocument=se.isDocument;R.isMap=se.isMap;R.isNode=se.isNode;R.isPair=se.isPair;R.isScalar=se.isScalar;R.isSeq=se.isSeq;R.Pair=Od.Pair;R.Scalar=jd.Scalar;R.YAMLMap=$d.YAMLMap;R.YAMLSeq=Hd.YAMLSeq;R.CST=Ld;R.Lexer=Md.Lexer;R.LineCounter=Dd.LineCounter;R.Parser=Fd.Parser;R.parse=fi.parse;R.parseAllDocuments=fi.parseAllDocuments;R.parseDocument=fi.parseDocument;R.stringify=fi.stringify;R.visit=ds.visit;R.visitAsync=ds.visitAsync});import Qh from"path";import br from"node:path";import{createHash as ec}from"crypto";function M(i){throw new TypeError(`Value is not valid canonical JSON: ${i}`)}function tc(i,e){e.has(i)&&M("cyclic structures are not supported"),e.add(i);try{let t=Object.keys(i);for(let n=0;n<i.length;n+=1)Object.prototype.hasOwnProperty.call(i,n)||M("sparse arrays are not supported");return(t.length!==i.length||t.some((n,r)=>n!==String(r)))&&M("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(i).length>0&&M("symbol properties are not supported"),`[${i.map(n=>ki(n,e)).join(",")}]`}finally{e.delete(i)}}function ic(i,e){let t=Object.getPrototypeOf(i);t!==Object.prototype&&t!==null&&M("only plain objects are supported"),e.has(i)&&M("cyclic structures are not supported"),Object.getOwnPropertySymbols(i).length>0&&M("symbol properties are not supported"),e.add(i);try{let n=Object.getOwnPropertyDescriptors(i);return`{${Object.keys(i).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&M("accessor properties are not supported"),`${JSON.stringify(o)}:${ki(s.value,e)}`}).join(",")}}`}finally{e.delete(i)}}function ki(i,e){if(i===null)return"null";switch(typeof i){case"boolean":return i?"true":"false";case"string":return JSON.stringify(i);case"number":return Number.isFinite(i)||M("numbers must be finite"),JSON.stringify(Object.is(i,-0)?0:i);case"object":return Array.isArray(i)?tc(i,e):ic(i,e);case"bigint":case"function":case"symbol":case"undefined":return M(`${typeof i} values are not supported`)}return M("unsupported value type")}function Ei(i){return ki(i,new Set)}function D(i,e){if(i.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(i))throw new TypeError("Canonical hash tag must not contain a line break");return ec("sha256").update(`${i}
143
+ ${Ei(e)}`).digest("hex")}var nc=/^acceptance-[a-f0-9]{64}$/u,rc=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),ac=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var ap=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Sr=Object.freeze({maxCriteria:1024}),oc="<!-- comet-native:acceptance-evidence:start -->",sc="<!-- comet-native:acceptance-evidence:end -->";function cc(i){return Array.from(i).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127})}function lc(i,e){let t=i.trim().replaceAll("\\","/");if(t.length===0||cc(t)||br.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(t)||t.split("/").includes(".."))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);let n=br.posix.normalize(t);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${e} references sensitive content`);if(!ac.test(n))throw new Error(`Acceptance evidence ${e} must reference a content-addressed typed receipt`);return n}function uc(i,e){if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`Acceptance evidence entry ${e} must be an object`);let t=i,n=Object.keys(t).filter(r=>!rc.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${e} has unknown field(s): ${n.join(", ")}`);return t}function fc(i){if(!Array.isArray(i))throw new Error("Native acceptance evidence block must be a JSON array");let e=new Set;return i.map((t,n)=>{let r=uc(t,n),a=r.acceptance_id;if(typeof a!="string"||!nc.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(e.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(e.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return lc(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=r.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(r,"skipped_reason")){if(typeof r.skipped_reason!="string"||r.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=r.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function dc(i){let e=fc([...i]).map(t=>({...t,evidence_refs:[...t.evidence_refs].sort()})).sort((t,n)=>t.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(e,null,2)}function kr(i){return[oc,dc(i),sc].join(`
144
+ `)}function X(i){return i!==0&&i!==0n&&i!=="0"}function W(i,e){return X(i.dev)&&X(e.dev)&&X(i.ino)&&X(e.ino)}function O(i,e){let t=X(i.dev)&&X(e.dev);if(t&&i.dev!==e.dev)return!1;let n=X(i.ino)&&X(e.ino);return n&&i.ino!==e.ino?!1:t&&n?!0:i.birthtime===e.birthtime}var hs=Nr(or(),1),sr=64*1024;var Bd=[".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/**"],ps={include:["**/*"],exclude:[...Bd],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};import{constants as di,promises as me}from"fs";var q=class extends Error{reason;constructor(e,t,n){super(t,n),this.name="RaceSafeReadError",this.reason=e}};function cr(i){return"birthtimeNs"in i&&typeof i.birthtimeNs=="bigint"?i.birthtimeNs:i.birthtimeMs}function ms(i){return"ctimeNs"in i&&typeof i.ctimeNs=="bigint"?i.ctimeNs:i.ctimeMs}function ct(i){return{dev:i.dev,ino:i.ino,birthtime:cr(i)}}function hi(i,e){let t=ct(i),n=ct(e);return W(t,n)?O(t,n):O(t,n)&&cr(i)===cr(e)&&ms(i)===ms(e)&&i.size===e.size}async function lt(i,e,t={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=t.label??"file",r=t.bigint===!0,a=await me.lstat(i,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new q("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new q("too-large",`${n} exceeds ${e} bytes`);let o=await me.realpath(i);await t.verify?.("pre-open",{realPath:o,identity:ct(a)});let s=process.platform==="win32"?di.O_RDONLY:di.O_RDONLY|di.O_NOFOLLOW|di.O_NONBLOCK,c;try{c=await me.open(i,s)}catch(l){throw l.code==="ELOOP"?new q("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,h,u]=await Promise.all([c.stat({bigint:r}),me.lstat(i,{bigint:r}),me.realpath(i)]);if(!l.isFile()||!h.isFile()||h.isSymbolicLink()||u!==o||!hi(a,l)||!hi(a,h))throw new q("changed",`${n} changed while opening`);await t.verify?.("post-open",{realPath:u,identity:ct(l)}),await t.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let N=e+1-m,{bytesRead:b}=await c.read(g,0,Math.min(g.length,N),null);if(b===0)break;if(m+=b,m>e)throw new q("too-large",`${n} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,b)))}await t.hooks?.beforeFinalCheck?.();let[d,p,w]=await Promise.all([c.stat({bigint:r}),me.lstat(i,{bigint:r}),me.realpath(i)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!hi(a,d)||!hi(a,p))throw new q("changed",`${n} changed while reading`);return await t.verify?.("post-read",{realPath:w,identity:ct(d)}),{bytes:Buffer.concat(f,m),stat:d,realPath:w}}finally{await c.close()}}var Wm=16*1024;import{promises as fr}from"fs";import Te from"path";import Gd from"os";var ks=".comet/config.yaml";async function Ss(i){try{return await fr.lstat(i),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ud(i){try{let e=await fr.readFile(i,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function dr(i){let e=Te.resolve(i);try{(await fr.stat(e)).isDirectory()||(e=Te.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let t=e,n=Te.resolve(Gd.homedir());for(;;){if(!(e===n&&t!==n)){let o=Te.join(e,...ks.split("/")),s=e===t||await Ud(o);if(await Ss(o)&&s)return e}if(await Ss(Te.join(e,".git")))return e;let a=Te.dirname(e);if(a===e)return t;e=a}}import{createHash as nh}from"crypto";function V(i){return nh("sha256").update(i).digest("hex")}var xv={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var Tv=8*1024*1024;var Iv=64*1024,_v=64*1024;var Ov={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},jv={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var $v=(1n<<256n)-1n;var ut=1024*1024;import Xh from"path";var xs=Nr(or(),1);var vr=1024*1024;import{AsyncLocalStorage as ah}from"async_hooks";var ng=16*1024;var rg=new ah;import{TextDecoder as sh}from"util";var dg=256*1024,hg=1024*1024,pg=16*1024;var mg=64*1024*1024;var vg=new sh("utf-8",{fatal:!0});var mw=256*1024;var Aw={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 Fw=16*1024;var Ts=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],ly=new Set(Ts),gh=new Set([...Ts,"minimum_runtime_version","revision"]),uy=new Set([...gh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]);var vi=class extends Error{constructor(t,n,r){super(`Native change ${t} revision conflict: expected ${n}, actual ${r}`);this.change=t;this.expectedRevision=n;this.actualRevision=r;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},gi=class extends Error{constructor(t,n,r,a,o,s=null,c=null){super(`Native change ${t} 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=t;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"},fy=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
145
+ `);var dy=256*1024;var yh=["Outcome","Scope","Non-goals","Acceptance examples"],wy=[...yh,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var Nh=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 _s="scoped-text-safety",bh=1,Sh=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var kh="comet.native.checker-policy.v1";var Iy=D(kh,{policy:_s,version:bh,limits:Sh,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Eh=["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"],_y=new Set(Eh);var Rh=ut,Yy=3*Rh;var Os={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:[]},Ph=V("comet-native-runtime:v3:semantic-repair-budget"),CN=[{skillVersion:"2",skillHash:V("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:V("comet-native-runtime:v1")}];var $s=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],sb=new Set($s),$h=new Set([...$s,"minimum_runtime_version","revision"]),cb=new Set([...$h,"operation"]),lb=512*1024,Hh=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),ub=new Set([...Hh,"implementationScopeHash","repairScopeHash","repairStagnation"]);var gb={maxAcceptanceCriteria:Sr.maxCriteria};var Sb={maxSpecs:64,maxFileBytes:vr,maxTotalBytes:4*1024*1024};import{execFile as zh,spawn as cS}from"node:child_process";import{promisify as Wh}from"node:util";var Ob={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var tS=512*1024;var SS=64*1024;var kS=3600*1e3;var ES=Wh(zh);var CS=["$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 yi=class extends Error{details;constructor(e){let t=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(t),this.name="NativeVerificationReceiptBindingError",this.details=e}};var fk={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var kk=16*1024*1024,Ek=256*1024,Ck=16*1024;var Ak=16*1024;var Fk=16*1024;var AE=16*1024*1024,Ni=class extends Error{constructor(t,n,r,a){super(`Canonical spec conflict for ${t}: expected ${n??"(missing)"}, actual ${r??"(missing)"}`);this.capability=t;this.expectedHash=n;this.actualHash=r;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},bi=class extends Error{constructor(t,n=t.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${t.findingCodes.join(", ")}`){super(n);this.preflight=t;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var ME=10*1024*1024,z=class extends Error{};function Ls(i,e){let t=i.flatMap((n,r)=>n===e?[r]:[]);if(t.length>1)throw new z(`${e} may only be provided once`);return t.length===0?!1:(i.splice(t[0],1),!0)}function Si(i,e){let t=i.flatMap((a,o)=>a===e?[o]:[]);if(t.length>1)throw new z(`${e} may only be provided once`);if(t.length===0)return;let n=t[0],r=i[n+1];if(r===void 0||r.startsWith("--"))throw new z(`${e} requires a value`);return i.splice(n,2),r}function Ms(i){if(i.length>0)throw new z(`Unexpected argument: ${i[0]}`)}function Ds(i,e){let t=i.shift();if(!t||t.startsWith("--"))throw new z(`${e} is required`);return t}async function Fs(i){return i?Xh.resolve(i):dr(process.cwd())}function Bs(i,e,t){return{command:i,exitCode:0,data:e,text:t??JSON.stringify(e,null,2)+`
146
146
  `}}async function qs(i,e){try{let{bytes:t}=await lt(i,e,{label:"Acceptance evidence entries file"});return t.toString("utf8")}catch(t){throw t instanceof q?t.reason==="not-regular-file"?new Error(`Acceptance evidence entries path is not a regular file: ${i}`,{cause:t}):t.reason==="too-large"?new Error(`Acceptance evidence entries file exceeds ${e} bytes: ${i}`,{cause:t}):new Error(`Acceptance evidence entries file changed while reading: ${i}`,{cause:t}):t}}async function Vs(i){let e=[],t=0;for await(let n of process.stdin){let r=Buffer.isBuffer(n)?n:Buffer.from(String(n));if(t+=r.byteLength,t>i)throw new Error(`Acceptance evidence entries on stdin exceed ${i} bytes`);e.push(r)}return Buffer.concat(e).toString("utf8")}function zs(i,e){if(e instanceof z)return{command:i,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Ni)return{command:i,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof bi)return{command:i,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof vi)return{command:i,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof gi)return{command:i,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 yi)return{command:i,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Error){let t=e.code;if(t&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(t))return{command:i,exitCode:70,error:{code:"internal",message:e.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:i,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:e.message}}}return{command:i,exitCode:70,error:{code:"internal",message:String(e)}}}function Ws(i,e){return e?{exitCode:i.exitCode,stdout:JSON.stringify({command:i.command,exitCode:i.exitCode,...i.data===void 0?{}:{data:i.data},...i.error===void 0?{}:{error:i.error}})+`
147
- `}:i.error?{exitCode:i.exitCode,stderr:i.error.message}:{exitCode:i.exitCode,stdout:i.text}}async function Js(i,e){let t=Ds(i,"evidence subcommand");if(t==="format"){let n=Si(i,"--entries");Ms(i);let r;if(n)r=await qs(Xh.resolve(n),ut);else{if(process.stdin.isTTY)throw new z("evidence format requires acceptance evidence entries JSON on stdin, or --entries <path>");r=await Vs(ut)}let a;try{a=JSON.parse(r)}catch(s){throw new Error(`Acceptance evidence entries must be valid JSON: ${s.message}`,{cause:s})}if(!Array.isArray(a))throw new Error("Acceptance evidence entries must be a JSON array");let o=kr(a);return Bs("evidence format",{block:o},`${o}
148
- `)}throw new z(`Unknown evidence command: ${t}`)}function Qh(i){return{exitCode:i.exitCode,stdout:JSON.stringify({command:i.command,exitCode:i.exitCode,...i.data===void 0?{}:{data:i.data},...i.error===void 0?{}:{error:i.error}})+`
149
- `}}async function Ks(i,e,t=process.argv.slice(2)){let n=t.indexOf("--"),r=n<0?[...t]:t.slice(0,n),a=n<0?[]:t.slice(n),o=r.includes("--json"),s,c;try{Ls(r,"--json"),s=Si(r,"--project-root");let h=[...r,...a],u=await Fs(s);c=await e(h,u)}catch(h){c=zs(i,h)}let l=o?Qh(c):Ws(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
147
+ `}:i.error?{exitCode:i.exitCode,stderr:i.error.message}:{exitCode:i.exitCode,stdout:i.text}}async function Js(i,e){let t=Ds(i,"evidence subcommand");if(t==="format"){let n=Si(i,"--entries");Ms(i);let r;if(n)r=await qs(Qh.resolve(n),ut);else{if(process.stdin.isTTY)throw new z("evidence format requires acceptance evidence entries JSON on stdin, or --entries <path>");r=await Vs(ut)}let a;try{a=JSON.parse(r)}catch(s){throw new Error(`Acceptance evidence entries must be valid JSON: ${s.message}`,{cause:s})}if(!Array.isArray(a))throw new Error("Acceptance evidence entries must be a JSON array");let o=kr(a);return Bs("evidence format",{block:o},`${o}
148
+ `)}throw new z(`Unknown evidence command: ${t}`)}function Zh(i){return{exitCode:i.exitCode,stdout:JSON.stringify({command:i.command,exitCode:i.exitCode,...i.data===void 0?{}:{data:i.data},...i.error===void 0?{}:{error:i.error}})+`
149
+ `}}async function Ks(i,e,t=process.argv.slice(2)){let n=t.indexOf("--"),r=n<0?[...t]:t.slice(0,n),a=n<0?[]:t.slice(n),o=r.includes("--json"),s,c;try{Ls(r,"--json"),s=Si(r,"--project-root");let h=[...r,...a],u=await Fs(s);c=await e(h,u)}catch(h){c=zs(i,h)}let l=o?Zh(c):Ws(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 Ks("evidence",Js);
@@ -139,14 +139,14 @@ ${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(ge(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(kc(i.key)&&!ge(i.sep,"newline")){let o=Ye(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(ge(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ye(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]}):ge(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&&!ge(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||ge(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=Ye(r);Sc(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=Ye(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=Ye(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())}}};Ec.Parser=ta});var xc=w(Lt=>{"use strict";var Cc=qr(),Zh=At(),$t=It(),ep=Fn(),tp=C(),ip=ea(),Rc=ia();function Pc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new ip.LineCounter||null,prettyErrors:e}}function np(t,e={}){let{lineCounter:i,prettyErrors:n}=Pc(e),r=new Rc.Parser(i?.addNewLine),a=new Cc.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 Ac(t,e={}){let{lineCounter:i,prettyErrors:n}=Pc(e),r=new Rc.Parser(i?.addNewLine),a=new Cc.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 rp(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=Ac(t,i);if(!r)return null;if(r.warnings.forEach(a=>ep.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 ap(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 tp.isDocument(t)&&!n?t.toString(i):new Zh.Document(t,n,i).toString(i)}Lt.parse=rp;Lt.parseAllDocuments=np;Lt.parseDocument=Ac;Lt.stringify=ap});var ra=w(P=>{"use strict";var op=qr(),sp=At(),cp=Sr(),na=It(),lp=dt(),we=C(),up=he(),fp=T(),dp=me(),hp=ve(),pp=Bi(),mp=Qr(),vp=ea(),gp=ia(),Wi=xc(),Tc=ct();P.Composer=op.Composer;P.Document=sp.Document;P.Schema=cp.Schema;P.YAMLError=na.YAMLError;P.YAMLParseError=na.YAMLParseError;P.YAMLWarning=na.YAMLWarning;P.Alias=lp.Alias;P.isAlias=we.isAlias;P.isCollection=we.isCollection;P.isDocument=we.isDocument;P.isMap=we.isMap;P.isNode=we.isNode;P.isPair=we.isPair;P.isScalar=we.isScalar;P.isSeq=we.isSeq;P.Pair=up.Pair;P.Scalar=fp.Scalar;P.YAMLMap=dp.YAMLMap;P.YAMLSeq=hp.YAMLSeq;P.CST=pp;P.Lexer=mp.Lexer;P.LineCounter=vp.LineCounter;P.Parser=gp.Parser;P.parse=Wi.parse;P.parseAllDocuments=Wi.parseAllDocuments;P.parseDocument=Wi.parseDocument;P.stringify=Wi.stringify;P.visit=Tc.visit;P.visitAsync=Tc.visitAsync});import{promises as dv}from"fs";import ot from"path";var jl=null;function Hl(t,e){let i=t;for(let n of e)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function Ha(t,e){return(...i)=>{let n=jl;if(n===null)return e(...i);let r=Hl(`async:${t}`,i),a=n.entries.get(r);if(a)return a.value;let o=e(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as $l}from"fs";var Ll=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),Ml=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Ma=["file_path","filePath","path","target_file","targetFile"],Da=["file_paths","filePaths","paths","files","targets"],Fa=["operations","edits"],Dl=["patch","diff","patchText","patch_text","changes"];function kn(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $a(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Fl(t){for(let e of["tool_name","toolName","tool","name"]){let i=t[e];if(typeof i=="string"&&i.trim())return i.trim()}return null}function Bl(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function ql(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return Bl(t[e]);return t}function La(t){let e=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of t.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function Se(t,e){if(typeof e=="string"){let i=e.trim();i&&t.push(i);return}if(Array.isArray(e)){for(let i of e)Se(t,i);return}if(kn(e)){for(let i of Ma)Se(t,e[i]);for(let i of Da)Se(t,e[i]);for(let i of Fa)Se(t,e[i])}}function Vl(t,e){let i=[],n=[e,t].filter(kn);for(let r of n){for(let a of Ma)Se(i,r[a]);for(let a of Da)Se(i,r[a]);for(let a of Fa)Se(i,r[a]);for(let a of Dl){let o=r[a];typeof o=="string"&&i.push(...La(o))}}return typeof e=="string"&&i.push(...La(e)),[...new Set(i)]}function st(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(t)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!kn(i))return{intent:"unknown",targets:[],toolName:null};let n=Fl(i),r=Vl(i,ql(i));return n&&Ll.has($a(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n}:n&&Ml.has($a(n))?{intent:"non-write",targets:[],toolName:n}:n?{intent:"unknown",targets:r,toolName:n}:{intent:r.length>0?"write":"unknown",targets:r,toolName:null}}function Ba(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return st("",t);try{return st($l(0,"utf8"),t)}catch{return st("",t)}}var ka=ja(ra(),1);import{promises as Vm}from"fs";import $e from"path";import{createHash as bp}from"node:crypto";import{promises as K}from"node:fs";import F from"node:path";import{TextDecoder as Sp}from"node:util";var wp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),yp=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Np(t){return t.toLowerCase().startsWith(".env")}function Mt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Np(n))?"environment-file":i.some(n=>yp.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>wp.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function ye(t){return t!==0&&t!==0n&&t!=="0"}function J(t,e){return ye(t.dev)&&ye(e.dev)&&ye(t.ino)&&ye(e.ino)}function I(t,e){let i=ye(t.dev)&&ye(e.dev);if(i&&t.dev!==e.dev)return!1;let n=ye(t.ino)&&ye(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Ki=1024*1024;function aa(t,e){let i=F.relative(t,e);return i===""||!F.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${F.sep}`)}function kp(t){let e=F.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})||F.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=Mt(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 Ep(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Cp(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 J(i,n)?I(i,n):I(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ic(t){let e=await K.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await K.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Rp(t,e){let i=F.resolve(t),n=F.resolve(e);if(!aa(i,n))throw new Error("Native artifact path is outside its root");let r=[await Ic(i)],a=i;for(let o of F.relative(i,n).split(F.sep).filter(Boolean)){a=F.join(a,o);let s=await Ic(a);if(!aa(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function _c(t){for(let e of t){let i=await K.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Cp(e,i)||await K.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function xe(t){let e=kp(t.ref),i=Ep(t.maxBytes??Ki),n=F.resolve(t.root,...e.split("/")),r=await Rp(t.root,F.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await K.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 K.realpath(n);if(!aa(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await K.open(n,"r");try{let[c,l,d]=await Promise.all([s.stat(),K.lstat(n),K.realpath(n)]);if(await _c(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(),K.lstat(n),K.realpath(n)]);if(await _c(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 Sp("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:bp("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var sa=ja(ra(),1);import Gi from"path";var Xi=64*1024,Ui=1024,Yi=64,jc=5,Pp=[".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/**"],te={include:["**/*"],exclude:[...Pp],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Ap(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 Xe(t){let e=Ap(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Hc(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 ca(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 Dt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function $c(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 Oc(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 oa(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 xp(t){if(t===void 0)return{...te,include:[...te.include],exclude:[...te.exclude]};let e=Dt(t,"native.snapshot");return{include:Oc(e.include,"native.snapshot.include",te.include),exclude:Oc(e.exclude,"native.snapshot.exclude",te.exclude),max_files:oa(e.max_files,te.max_files,"native.snapshot.max_files"),max_total_bytes:oa(e.max_total_bytes,te.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:oa(e.max_duration_ms,te.max_duration_ms,"native.snapshot.max_duration_ms")}}function Tp(t){if(t===void 0)return;let e=Dt(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=Dt(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:Xe(n),toArtifactRoot:Xe(r),stage:a,...o?{cleanup:o}:{}}}function Ip(t){let e=Dt(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??jc;if(!Number.isSafeInteger(r)||r<1)throw new Error("native.max_verify_failures must be a positive integer");let a=Tp(e.pending_root_move);return{artifact_root:Xe(e.artifact_root),language:$c(e.language,"en","native.language"),clarification_mode:i,archive_confirmation:n,max_verify_failures:r,snapshot:xp(e.snapshot),...a?{pending_root_move:a}:{}}}function _p(t){let e=Dt(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:Hc(e.artifact_layout),language:$c(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Op(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function jp(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,sa.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=Op(r.ambient_resume),o=r.native===void 0?void 0:Ip(r.native),s=r.classic===void 0?void 0:_p(r.classic),c=jp(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}import{createHash as $p}from"crypto";import{promises as nn}from"fs";import Ne from"path";import{constants as en,promises as Te}from"fs";var ie=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function la(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Lc(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Ft(t){return{dev:t.dev,ino:t.ino,birthtime:la(t)}}function tn(t,e){let i=Ft(t),n=Ft(e);return J(i,n)?I(i,n):I(i,n)&&la(t)===la(e)&&Lc(t)===Lc(e)&&t.size===e.size}async function Qe(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 Te.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new ie("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ie("too-large",`${n} exceeds ${e} bytes`);let o=await Te.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Ft(a)});let s=process.platform==="win32"?en.O_RDONLY:en.O_RDONLY|en.O_NOFOLLOW|en.O_NONBLOCK,c;try{c=await Te.open(t,s)}catch(l){throw l.code==="ELOOP"?new ie("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),Te.lstat(t,{bigint:r}),Te.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!tn(a,l)||!tn(a,d))throw new ie("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Ft(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 ie("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}),Te.lstat(t,{bigint:r}),Te.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!tn(a,h)||!tn(a,p))throw new ie("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Ft(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:y}}finally{await c.close()}}function Hp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ua(t,e){let i=Ne.relative(t,e);return i===""||!Ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ne.sep}`)}async function Mc(t,e){let i=Ne.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 Dc(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=Ne.join(r,i[a]);let o;try{o=await nn.lstat(r)}catch(d){if(Hp(d))return{exists:!1,kind:"missing"};throw d}let s=Ne.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(!ua(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 Bt(t,e,i){let n=ca(e,i.label),r=Ne.resolve(t),a=await Mc(r,i.label),o=n.split("/"),s=Ne.resolve(r,...o);if(!ua(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Dc(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Ze(t,e,i,n){let r=await Bt(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 Mc(r.projectRoot,n.label);return Qe(r.target,i,{...n,verify:async(o,s)=>{if(!ua(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Dc(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var qt=".comet/config.yaml";function Lp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function fa(t,e={}){return(await rn(t,e)).document}async function Mp(t){try{return(await Ze(t,qt,Xi,{label:qt})).bytes}catch(e){if(Lp(e))return null;throw e}}function Dp(t){return t?{exists:!0,sha256:$p("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function rn(t,e={}){let i=await Mp(t);return{document:i?Zi(i.toString("utf8"),e):null,identity:Dp(i)}}var Qw=16*1024;import{promises as et}from"fs";import A from"path";import Vp from"os";var pa=".comet/config.yaml";async function ha(t){try{return await et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function zp(t){try{let e=await et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Vt(t,e){let i=A.relative(t,e);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function zt(t){let e=[],i=t;for(;!await ha(i);){let r=A.dirname(i);if(r===i)break;e.push(A.basename(i)),i=r}let n=await et.realpath(i);return A.resolve(n,...e.reverse())}async function Vc(t){try{return(await et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ma(t){let e=A.resolve(t);try{(await et.stat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=A.resolve(Vp.homedir());for(;;){if(!(e===n&&i!==n)){let o=A.join(e,...pa.split("/")),s=e===i||await zp(o);if(await ha(o)&&s)return e}if(await ha(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return i;e=a}}function va(t){return Xe(t)}async function Wp(t,e){let i=va(e),n=A.resolve(t,...i.split("/")),r=await et.realpath(t),a=await zt(n);if(!Vt(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function an(t,e){let i=va(e),n=await Wp(t,i),r=A.join(n,"comet");if(await Vc(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([zt(n),zt(r)]);if(!Vt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:A.resolve(t),configFile:A.join(t,...pa.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 ne(t,e){return Vt(A.resolve(t),A.resolve(e))}async function H(t,e){let i=A.resolve(t),n=A.resolve(e);if(!Vt(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Vc(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([zt(i),zt(n)]);if(!Vt(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var on=Qi;async function tt(t){let e=(await fa(t))?.config??null;return e?.native?e:null}import{AsyncLocalStorage as Gp}from"async_hooks";var Sy=16*1024;var ky=new Gp;import{TextDecoder as nm}from"util";import{createHash as Up}from"node:crypto";import{constants as sn,promises as G}from"node:fs";import U from"node:path";import{TextDecoder as Yp}from"node:util";function ln(t,e){let i=U.relative(t,e);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}function Xp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function Qp(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 cn(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 wa(t,e){let i=await G.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await G.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function em(t,e,i){let n=U.resolve(t),r=U.resolve(e);if(!ln(n,r))throw new Error(`${i} is outside its managed root`);let a=[await wa(n,i)],o=n;for(let s of U.relative(n,r).split(U.sep).filter(Boolean)){await Ie(a,i),o=U.join(o,s);let c=await wa(o,i);if(!ln(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ie(a,i),a}async function Ie(t,e){for(let i of t){let n=await G.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Qp(i,n)||await G.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function tm(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 it(t){let e=Xp(t.maxBytes),i=U.resolve(t.file),n=await em(t.root,U.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(d=>wa(U.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ie(n,t.label);let a=await G.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 G.realpath(i);if(!ln(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(d=>ln(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?sn.O_RDONLY:sn.O_RDONLY|sn.O_NOFOLLOW|sn.O_NONBLOCK,l=await G.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([G.lstat(i),G.realpath(i)]);if(await Ie(n,t.label),await Ie(r,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!cn(o,d)||!cn(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await tm(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([l.stat(),G.lstat(i),G.realpath(i)]);if(await Ie(n,t.label),await Ie(r,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!cn(o,g)||!cn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:Up("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function zc(t){let e=await it(t),i;try{i=new Yp("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}}var Dy=256*1024,Fy=1024*1024,By=16*1024;var qy=64*1024*1024;var Vy=new nm("utf-8",{fatal:!0});import fn from"path";import{createHash as am}from"crypto";function B(t){return am("sha256").update(t).digest("hex")}var sN={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},sm=1e3,cm=8*1024*1024,lm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,um=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),fm=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),dm=new Set(["schema","include","exclude","hash"]),hm=new Set(["provider","gitSelection","physicalSelection","projection"]),pm=new Set(["provider","selection"]),mm=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),vm=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),gm=new Set(["schema","status","before","after"]),wm=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),ym=new Set(["path","hash","size","type","gitObjectId"]),Nm=new Set(["path","size","type","reason"]),bm=new Set(["ref","hash","count"]),Sm=new Set(["change-created","legacy-migration","explicit"]),km=new Set(["file","directory","other"]),Em=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"]),dn=/^[a-f0-9]{64}$/u,Cm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var cN=64*1024,lN=64*1024;var uN={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},fN={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function un(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var dN=(1n<<256n)-1n;function Rm(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 Pm(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
143
- `)}function Am(t,e){return B(`comet.native.snapshot-policy.v1
144
- ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Na(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 xm(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Uc(t){let e=on(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?xm(r):void 0;if(a&&!a())return!1;let o=Na(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=Na(i,c,a),o===null||o.size===0)return!1}return Na(i,o,a)?.has(i.length)??!1}}function Tm(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>on(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>on(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=Am(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(Uc),excludeMatchers:i.map(Uc),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 q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function V(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function rt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function re(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Qc(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=fn.posix.normalize(t);if(i!==t||fn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function Im(t,e){let i=q(t,`Native snapshot entry ${e}`);V(i,ym,`Native snapshot entry ${e}`);let n=Qc(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!dn.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:re(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Cm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function _m(t,e){let i=q(t,`Native snapshot omission ${e}`);if(V(i,Nm,`Native snapshot omission ${e}`),!km.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Em.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Qc(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:re(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function Om(t){let e=q(t,"Native snapshot omission overflow");if(V(e,bm,"Native snapshot omission overflow"),typeof e.hash!="string"||!dn.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:rt(e.count,"Native snapshot omission overflow count")}}function nt(t,e){let i=q(t,e);if(V(i,vm,e),typeof i.hash!="string"||!dn.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=re(i.recordCount,`${e} recordCount`),r=re(i.storedRecordCount,`${e} storedRecordCount`),a=re(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 Yc(t){let e=q(t,"Native Git selection evidence");if(V(e,mm,"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=nt(e.stageBefore,"Native Git selection stageBefore"),n=nt(e.combined,"Native Git selection combined"),r=nt(e.stageAfter,"Native Git selection stageAfter"),a=nt(e.finalStageBefore,"Native Git selection finalStageBefore"),o=nt(e.finalCombined,"Native Git selection finalCombined"),s=nt(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!un(i,r)||!un(r,a)||!un(n,o)||!un(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 Xc(t,e){let i=q(t,e);if(V(i,wm,e),typeof i.hash!="string"||!dn.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=re(i.visitedNodeCount,`${e} visitedNodeCount`),r=re(i.recordCount,`${e} recordCount`),a=re(i.storedRecordCount,`${e} storedRecordCount`),o=re(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 jm(t){let e=q(t,"Native physical selection evidence");if(V(e,gm,"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=Xc(e.before,"Native physical selection before"),n=Xc(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Rm(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 Zc(t){let e=q(t,"Native content snapshot manifest");if(V(e,um,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Sm.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=q(e.capture,"Native content snapshot capture");if(V(v,hm,"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:Yc(v.gitSelection),b=v.physicalSelection===void 0?void 0:jm(v.physicalSelection),x=null;if(v.projection!==void 0){let M=q(v.projection,"Native content snapshot projection");if(V(M,pm,"Native content snapshot projection"),M.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");x={provider:"git",...M.selection===void 0?{}:{selection:Yc(M.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=q(e.limits,"Native content snapshot limits");V(n,fm,"Native content snapshot limits");let r={maxFiles:rt(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:rt(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:rt(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:rt(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:rt(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=q(e.policy,"Native snapshot policy");if(V(v,dm,"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=Tm({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(Im),s=e.omitted.map(_m),c=re(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Om(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>sm||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(Pm(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Hm(t,e){if(!lm.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=fn.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return fn.join(i,"runtime","baseline-manifest.json")}async function el(t,e){let i=Hm(t,e);await H(t.nativeRoot,i);try{let n=await zc({root:t.nativeRoot,file:i,maxBytes:cm,label:"Native baseline snapshot manifest"});return Zc(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var rb=256*1024;var gb={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 xb=16*1024;var Oe="comet.native.v3",je="comet.native.v2",He="comet.native.v1";var il=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],zm=new Set(il),nl=new Set([...il,"minimum_runtime_version","revision"]),Wm=new Set([...nl,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Jm=new Set(["capability","operation","source","base_hash"]),Km=new Set(["shape","build","verify","archive"]),Gm=new Set(["implicit","confirmed"]),Um=new Set(["pending","pass","fail"]),Me="comet-state.yaml",Sa=/^[a-f0-9]{64}$/u,rl=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ym=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,hn=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"},Le=class extends Error{constructor(i,n){super(i!==Oe||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"},pn=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"},mn=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"},Yb=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
145
- `);function Jt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function al(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 vn(t){if(!rl.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Xm(t){if(!rl.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ol(t,e){if(t.length===0||$e.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=Jt(t,`spec_changes[${e}]`);if(al(i,Jm,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Xm(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"&&ol(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"||!Sa.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"||!Sa.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 Ea(t,e){if(al(t,e,Me),typeof t.name!="string")throw new Error("Native change name is required");if(vn(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"||!Km.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&&!Gm.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"||!Um.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"&&ol(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 Ca(t){let e=Jt(t,Me);if(e.schema!==He)throw new Error(`Expected ${He}`);return{schema:He,...Ea(e,zm)}}function Wt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ba(t,e,i){if(t===null)return null;let n=typeof t=="string"?Ym.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 ev(t){if(t==null)return null;if(typeof t!="string"||!Sa.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function tv(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 Ra(t){let e=Jt(t,Me);if(e.schema!==je)throw new Error(`Expected ${je}`);if(Wt(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${je} minimum_runtime_version must be 2`);return{schema:je,minimum_runtime_version:2,revision:Wt(e.revision,"Native v2 revision"),...Ea(e,nl)}}function Pa(t){let e=Jt(t,Me);if(e.schema!==Oe){if(e.schema===He||e.schema===je){let o=e.schema===He?Ca(e):Ra(e);throw new hn(o.name,o.schema)}throw new Le(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Wt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Le(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Wt(e.revision,"Native revision"),r=Ea(e,Wm),a=ev(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:n,verification_protocol:tv(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:ba(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ba(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ba(e.partial_allowance,"Native partial_allowance","allowances")}}function iv(t){let e=Jt(t,Me);if(e.schema===He){let r=Ca(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Oe}`}}if(e.schema===je){let r=Ra(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Oe}`}}if(e.schema!==Oe){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 Le(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Wt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Le(e.schema,i).message};let n=Pa(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Y(t,e){vn(e);let i=$e.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Aa(t,e){let i=$e.join(Y(t,e),"runtime","schema-migration.json");await H(t.nativeRoot,i);try{return await Vm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var nv=256*1024;async function rv(t,e=$e.dirname(t)){let i=$e.relative(e,t).split($e.sep).join("/"),n=await xe({root:e,ref:i,maxBytes:nv}),r=(0,ka.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 av(t,e){let i=$e.join(Y(t,e),Me);await H(t.nativeRoot,i);let n=iv(await rv(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Aa(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 ov(t,n.state),n)}async function ov(t,e){if(await el(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function se(t,e){let i=await av(t,e);if(i.status==="migration-required")throw new hn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Le(i.schema,i.minimumRuntimeVersion);return i.state}import sv from"path";var xa="comet.selection.v2",cv=16*1024;function cl(t){return sv.join(t,".comet","current-change.json")}function lv(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function sl(t){return t===null||typeof t=="string"}function uv(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!lv(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!sl(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:xa,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==xa)throw new Error(`current change selection schema must be ${xa}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!sl(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function ll(t){let e;try{let n=cl(t),{bytes:r}=await Qe(n,cv,{label:"current change selection"});e=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...uv(e)}}var cS=16*1024;async function fv(t){let e=await ll(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(vn(e.selection.change),e.selection)}async function ul(t){let e=await fv(t);return e?(await se(t,e.change),e.change):null}function gn(t,e){let i=ot.relative(t,e);return i===""||!i.startsWith("..")&&!ot.isAbsolute(i)}function hv(t,e,i){return i.targets.length>0&&i.targets.every(n=>{let r=ot.resolve(t,n);return gn(t,r)?ot.relative(t,r).replaceAll("\\","/")===".comet/config.yaml"||gn(e,r):!0})}async function pv(t){let e=await tt(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let i=await an(t,e.native.artifact_root),n;try{n=await dv.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let r=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name))){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=await se(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var mv=Ha("nativeActiveContext",t=>pv(t));async function fl(){let{intent:t,targets:e}=await Ba();return{intent:t,targets:e}}async function dl(t,e,i){let n=await mv(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:hv(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let r;if(i){if(r=n.changes.find(s=>s.name===i),!r)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(n.changes.length===1)r=n.changes[0];else{let s=await ul(n.paths);if(r=n.changes.find(c=>c.name===s),!r)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(r.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!1,reason:`Hook write target could not be determined while Native change ${r.name} is in ${r.phase}; resume /comet-native before retrying`,workflow:"native",phase:r.phase,change:r.name};let a=!1,o=!1;for(let s of e.targets){let c=ot.resolve(t,s);if(!gn(t,c)){o=!0;continue}if(ot.relative(t,c).replaceAll("\\","/")===".comet/config.yaml"||gn(n.paths.nativeRoot,c)){a=!0;continue}return{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:r.phase,change:r.name}}return{allowed:!0,reason:a?"Native control artifact write":o?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}import Yv from"path";var gv=["Outcome","Scope","Non-goals","Acceptance examples"],_S=[...gv,"Constraints and invariants","Decisions","Open questions","Verification expectations"];import{createHash as wv}from"crypto";function X(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function yv(t,e){e.has(t)&&X("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)||X("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&X("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&X("symbol properties are not supported"),`[${t.map(n=>Ta(n,e)).join(",")}]`}finally{e.delete(t)}}function Nv(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&X("only plain objects are supported"),e.has(t)&&X("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&X("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))&&X("accessor properties are not supported"),`${JSON.stringify(o)}:${Ta(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Ta(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)||X("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?yv(t,e):Nv(t,e);case"bigint":case"function":case"symbol":case"undefined":return X(`${typeof t} values are not supported`)}return X("unsupported value type")}function Ia(t){return Ta(t,new Set)}function Q(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 wv("sha256").update(`${t}
146
- ${Ia(e)}`).digest("hex")}var bv=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 hl=1024*1024;var ml="scoped-text-safety",Sv=1,kv=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Ev="comet.native.checker-policy.v1";var YS=Q(Ev,{policy:ml,version:Sv,limits:kv,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Cv=["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"],XS=new Set(Cv);var Pv=hl,mk=3*Pv;var vl={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:[]},Av=B("comet-native-runtime:v3:semantic-repair-budget"),zk=[{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];var wl=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],EE=new Set(wl),jv=new Set([...wl,"minimum_runtime_version","revision"]),CE=new Set([...jv,"operation"]),RE=512*1024,Hv=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),PE=new Set([...Hv,"implementationScopeHash","repairScopeHash","repairStagnation"]);var TE=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),yl=Object.freeze({maxCriteria:1024});var LE={maxAcceptanceCriteria:yl.maxCriteria};var qE={maxSpecs:64,maxFileBytes:Ki,maxTotalBytes:4*1024*1024};import{execFile as Vv,spawn as AC}from"node:child_process";import{promisify as zv}from"node:util";var ZE={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var bC=512*1024;var qC=64*1024;var VC=3600*1e3;var zC=zv(Vv);var WC=["$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 yn=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 IR={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var VR=16*1024*1024,zR=256*1024,WR=16*1024;var _P=16*1024*1024,Nn=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"},bn=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 qP=10*1024*1024,ce=class extends Error{};function bl(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ce(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Sn(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ce(`${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 ce(`${e} requires a value`);return t.splice(n,2),r}function Sl(t){if(t.length>0)throw new ce(`Unexpected argument: ${t[0]}`)}async function kl(t){return t?Yv.resolve(t):ma(process.cwd())}function El(t,e){if(e instanceof ce)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Nn)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 bn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof pn)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 mn)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 yn)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 Cl(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}})+`
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=Ye(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=Ye(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())}}};Ec.Parser=ta});var xc=w(Lt=>{"use strict";var Cc=qr(),Zh=At(),$t=It(),ep=Fn(),tp=C(),ip=ea(),Rc=ia();function Pc(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new ip.LineCounter||null,prettyErrors:e}}function np(t,e={}){let{lineCounter:i,prettyErrors:n}=Pc(e),r=new Rc.Parser(i?.addNewLine),a=new Cc.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 Ac(t,e={}){let{lineCounter:i,prettyErrors:n}=Pc(e),r=new Rc.Parser(i?.addNewLine),a=new Cc.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 rp(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=Ac(t,i);if(!r)return null;if(r.warnings.forEach(a=>ep.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 ap(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 tp.isDocument(t)&&!n?t.toString(i):new Zh.Document(t,n,i).toString(i)}Lt.parse=rp;Lt.parseAllDocuments=np;Lt.parseDocument=Ac;Lt.stringify=ap});var ra=w(P=>{"use strict";var op=qr(),sp=At(),cp=Sr(),na=It(),lp=dt(),we=C(),up=he(),fp=T(),dp=me(),hp=ve(),pp=Bi(),mp=Qr(),vp=ea(),gp=ia(),Wi=xc(),Tc=ct();P.Composer=op.Composer;P.Document=sp.Document;P.Schema=cp.Schema;P.YAMLError=na.YAMLError;P.YAMLParseError=na.YAMLParseError;P.YAMLWarning=na.YAMLWarning;P.Alias=lp.Alias;P.isAlias=we.isAlias;P.isCollection=we.isCollection;P.isDocument=we.isDocument;P.isMap=we.isMap;P.isNode=we.isNode;P.isPair=we.isPair;P.isScalar=we.isScalar;P.isSeq=we.isSeq;P.Pair=up.Pair;P.Scalar=fp.Scalar;P.YAMLMap=dp.YAMLMap;P.YAMLSeq=hp.YAMLSeq;P.CST=pp;P.Lexer=mp.Lexer;P.LineCounter=vp.LineCounter;P.Parser=gp.Parser;P.parse=Wi.parse;P.parseAllDocuments=Wi.parseAllDocuments;P.parseDocument=Wi.parseDocument;P.stringify=Wi.stringify;P.visit=Tc.visit;P.visitAsync=Tc.visitAsync});import{promises as hv}from"fs";import ot from"path";var jl=null;function Hl(t,e){let i=t;for(let n of e)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function Ha(t,e){return(...i)=>{let n=jl;if(n===null)return e(...i);let r=Hl(`async:${t}`,i),a=n.entries.get(r);if(a)return a.value;let o=e(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as $l}from"fs";var Ll=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),Ml=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Ma=["file_path","filePath","path","target_file","targetFile"],Da=["file_paths","filePaths","paths","files","targets"],Fa=["operations","edits"],Dl=["patch","diff","patchText","patch_text","changes"];function kn(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function $a(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Fl(t){for(let e of["tool_name","toolName","tool","name"]){let i=t[e];if(typeof i=="string"&&i.trim())return i.trim()}return null}function Bl(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function ql(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return Bl(t[e]);return t}function La(t){let e=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of t.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function Se(t,e){if(typeof e=="string"){let i=e.trim();i&&t.push(i);return}if(Array.isArray(e)){for(let i of e)Se(t,i);return}if(kn(e)){for(let i of Ma)Se(t,e[i]);for(let i of Da)Se(t,e[i]);for(let i of Fa)Se(t,e[i])}}function Vl(t,e){let i=[],n=[e,t].filter(kn);for(let r of n){for(let a of Ma)Se(i,r[a]);for(let a of Da)Se(i,r[a]);for(let a of Fa)Se(i,r[a]);for(let a of Dl){let o=r[a];typeof o=="string"&&i.push(...La(o))}}return typeof e=="string"&&i.push(...La(e)),[...new Set(i)]}function st(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(t)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!kn(i))return{intent:"unknown",targets:[],toolName:null};let n=Fl(i),r=Vl(i,ql(i));return n&&Ll.has($a(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n}:n&&Ml.has($a(n))?{intent:"non-write",targets:[],toolName:n}:n?{intent:"unknown",targets:r,toolName:n}:{intent:r.length>0?"write":"unknown",targets:r,toolName:null}}function Ba(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return st("",t);try{return st($l(0,"utf8"),t)}catch{return st("",t)}}var ka=ja(ra(),1);import{promises as zm}from"fs";import $e from"path";import{createHash as bp}from"node:crypto";import{promises as K}from"node:fs";import F from"node:path";import{TextDecoder as Sp}from"node:util";var wp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),yp=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Np(t){return t.toLowerCase().startsWith(".env")}function Mt(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Np(n))?"environment-file":i.some(n=>yp.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>wp.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function ye(t){return t!==0&&t!==0n&&t!=="0"}function J(t,e){return ye(t.dev)&&ye(e.dev)&&ye(t.ino)&&ye(e.ino)}function I(t,e){let i=ye(t.dev)&&ye(e.dev);if(i&&t.dev!==e.dev)return!1;let n=ye(t.ino)&&ye(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Ki=1024*1024;function aa(t,e){let i=F.relative(t,e);return i===""||!F.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${F.sep}`)}function kp(t){let e=F.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})||F.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=Mt(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 Ep(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Cp(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 J(i,n)?I(i,n):I(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Ic(t){let e=await K.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await K.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Rp(t,e){let i=F.resolve(t),n=F.resolve(e);if(!aa(i,n))throw new Error("Native artifact path is outside its root");let r=[await Ic(i)],a=i;for(let o of F.relative(i,n).split(F.sep).filter(Boolean)){a=F.join(a,o);let s=await Ic(a);if(!aa(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function _c(t){for(let e of t){let i=await K.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!Cp(e,i)||await K.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function xe(t){let e=kp(t.ref),i=Ep(t.maxBytes??Ki),n=F.resolve(t.root,...e.split("/")),r=await Rp(t.root,F.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await K.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 K.realpath(n);if(!aa(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await K.open(n,"r");try{let[c,l,d]=await Promise.all([s.stat(),K.lstat(n),K.realpath(n)]);if(await _c(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(),K.lstat(n),K.realpath(n)]);if(await _c(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 Sp("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:bp("sha256").update(y).digest("hex"),text:N}}finally{await s.close()}}var sa=ja(ra(),1);import Gi from"path";var Xi=64*1024,Ui=1024,Yi=64,jc=5,Pp=[".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/**"],te={include:["**/*"],exclude:[...Pp],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function Ap(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 Xe(t){let e=Ap(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Hc(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 ca(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 Dt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function $c(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 Oc(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 oa(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 xp(t){if(t===void 0)return{...te,include:[...te.include],exclude:[...te.exclude]};let e=Dt(t,"native.snapshot");return{include:Oc(e.include,"native.snapshot.include",te.include),exclude:Oc(e.exclude,"native.snapshot.exclude",te.exclude),max_files:oa(e.max_files,te.max_files,"native.snapshot.max_files"),max_total_bytes:oa(e.max_total_bytes,te.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:oa(e.max_duration_ms,te.max_duration_ms,"native.snapshot.max_duration_ms")}}function Tp(t){if(t===void 0)return;let e=Dt(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=Dt(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:Xe(n),toArtifactRoot:Xe(r),stage:a,...o?{cleanup:o}:{}}}function Ip(t,e={}){let i=Dt(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??jc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Tp(i.pending_root_move);return{artifact_root:Xe(n),language:$c(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:xp(i.snapshot),...s?{pending_root_move:s}:{}}}function _p(t){let e=Dt(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:Hc(e.artifact_layout),language:$c(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function Op(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function jp(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,sa.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=Op(r.ambient_resume),o=r.native===void 0?void 0:Ip(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:_p(r.classic),c=jp(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}import{createHash as $p}from"crypto";import{promises as nn}from"fs";import Ne from"path";import{constants as en,promises as Te}from"fs";var ie=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function la(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Lc(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Ft(t){return{dev:t.dev,ino:t.ino,birthtime:la(t)}}function tn(t,e){let i=Ft(t),n=Ft(e);return J(i,n)?I(i,n):I(i,n)&&la(t)===la(e)&&Lc(t)===Lc(e)&&t.size===e.size}async function Qe(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 Te.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new ie("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new ie("too-large",`${n} exceeds ${e} bytes`);let o=await Te.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:Ft(a)});let s=process.platform==="win32"?en.O_RDONLY:en.O_RDONLY|en.O_NOFOLLOW|en.O_NONBLOCK,c;try{c=await Te.open(t,s)}catch(l){throw l.code==="ELOOP"?new ie("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,d,u]=await Promise.all([c.stat({bigint:r}),Te.lstat(t,{bigint:r}),Te.realpath(t)]);if(!l.isFile()||!d.isFile()||d.isSymbolicLink()||u!==o||!tn(a,l)||!tn(a,d))throw new ie("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:u,identity:Ft(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 ie("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}),Te.lstat(t,{bigint:r}),Te.realpath(t)]);if(!p.isFile()||p.isSymbolicLink()||y!==o||!tn(a,h)||!tn(a,p))throw new ie("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:y,identity:Ft(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:y}}finally{await c.close()}}function Hp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ua(t,e){let i=Ne.relative(t,e);return i===""||!Ne.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ne.sep}`)}async function Mc(t,e){let i=Ne.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 Dc(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=Ne.join(r,i[a]);let o;try{o=await nn.lstat(r)}catch(d){if(Hp(d))return{exists:!1,kind:"missing"};throw d}let s=Ne.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(!ua(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 Bt(t,e,i){let n=ca(e,i.label),r=Ne.resolve(t),a=await Mc(r,i.label),o=n.split("/"),s=Ne.resolve(r,...o);if(!ua(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Dc(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Ze(t,e,i,n){let r=await Bt(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 Mc(r.projectRoot,n.label);return Qe(r.target,i,{...n,verify:async(o,s)=>{if(!ua(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Dc(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var qt=".comet/config.yaml";function Lp(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function fa(t,e={}){return(await rn(t,e)).document}async function Mp(t){try{return(await Ze(t,qt,Xi,{label:qt})).bytes}catch(e){if(Lp(e))return null;throw e}}function Dp(t){return t?{exists:!0,sha256:$p("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function rn(t,e={}){let i=await Mp(t);return{document:i?Zi(i.toString("utf8"),e):null,identity:Dp(i)}}var Zw=16*1024;import{promises as et}from"fs";import A from"path";import zp from"os";var pa=".comet/config.yaml";async function ha(t){try{return await et.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Wp(t){try{let e=await et.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Vt(t,e){let i=A.relative(t,e);return i===""||!A.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${A.sep}`)}async function zt(t){let e=[],i=t;for(;!await ha(i);){let r=A.dirname(i);if(r===i)break;e.push(A.basename(i)),i=r}let n=await et.realpath(i);return A.resolve(n,...e.reverse())}async function Vc(t){try{return(await et.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function ma(t){let e=A.resolve(t);try{(await et.stat(e)).isDirectory()||(e=A.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=A.resolve(zp.homedir());for(;;){if(!(e===n&&i!==n)){let o=A.join(e,...pa.split("/")),s=e===i||await Wp(o);if(await ha(o)&&s)return e}if(await ha(A.join(e,".git")))return e;let a=A.dirname(e);if(a===e)return i;e=a}}function va(t){return Xe(t)}async function Jp(t,e){let i=va(e),n=A.resolve(t,...i.split("/")),r=await et.realpath(t),a=await zt(n);if(!Vt(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function an(t,e){let i=va(e),n=await Jp(t,i),r=A.join(n,"comet");if(await Vc(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([zt(n),zt(r)]);if(!Vt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:A.resolve(t),configFile:A.join(t,...pa.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 ne(t,e){return Vt(A.resolve(t),A.resolve(e))}async function H(t,e){let i=A.resolve(t),n=A.resolve(e);if(!Vt(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Vc(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([zt(i),zt(n)]);if(!Vt(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var on=Qi;async function tt(t){let e=(await fa(t))?.config??null;return e?.native?e:null}import{AsyncLocalStorage as Up}from"async_hooks";var ky=16*1024;var Ey=new Up;import{TextDecoder as rm}from"util";import{createHash as Yp}from"node:crypto";import{constants as sn,promises as G}from"node:fs";import U from"node:path";import{TextDecoder as Xp}from"node:util";function ln(t,e){let i=U.relative(t,e);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.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 Zp(t,e){return I({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function em(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function cn(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 wa(t,e){let i=await G.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await G.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function tm(t,e,i){let n=U.resolve(t),r=U.resolve(e);if(!ln(n,r))throw new Error(`${i} is outside its managed root`);let a=[await wa(n,i)],o=n;for(let s of U.relative(n,r).split(U.sep).filter(Boolean)){await Ie(a,i),o=U.join(o,s);let c=await wa(o,i);if(!ln(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ie(a,i),a}async function Ie(t,e){for(let i of t){let n=await G.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Zp(i,n)||await G.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function im(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 it(t){let e=Qp(t.maxBytes),i=U.resolve(t.file),n=await tm(t.root,U.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(d=>wa(U.resolve(d),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ie(n,t.label);let a=await G.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=em(a),s=await G.realpath(i);if(!ln(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(d=>ln(d.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?sn.O_RDONLY:sn.O_RDONLY|sn.O_NOFOLLOW|sn.O_NONBLOCK,l=await G.open(i,c);try{let d=await l.stat();await t.hooks?.afterOpen?.();let[u,f]=await Promise.all([G.lstat(i),G.realpath(i)]);if(await Ie(n,t.label),await Ie(r,t.label),!d.isFile()||!u.isFile()||u.isSymbolicLink()||f!==s||!cn(o,d)||!cn(o,u))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let m=await im(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[g,h,p]=await Promise.all([l.stat(),G.lstat(i),G.realpath(i)]);if(await Ie(n,t.label),await Ie(r,t.label),!h.isFile()||h.isSymbolicLink()||p!==s||!cn(o,g)||!cn(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:m,hash:Yp("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}async function zc(t){let e=await it(t),i;try{i=new Xp("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}}var Fy=256*1024,By=1024*1024,qy=16*1024;var Vy=64*1024*1024;var zy=new rm("utf-8",{fatal:!0});import fn from"path";import{createHash as om}from"crypto";function B(t){return om("sha256").update(t).digest("hex")}var cN={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},cm=1e3,lm=8*1024*1024,um=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fm=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),dm=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),hm=new Set(["schema","include","exclude","hash"]),pm=new Set(["provider","gitSelection","physicalSelection","projection"]),mm=new Set(["provider","selection"]),vm=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),gm=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),wm=new Set(["schema","status","before","after"]),ym=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Nm=new Set(["path","hash","size","type","gitObjectId"]),bm=new Set(["path","size","type","reason"]),Sm=new Set(["ref","hash","count"]),km=new Set(["change-created","legacy-migration","explicit"]),Em=new Set(["file","directory","other"]),Cm=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"]),dn=/^[a-f0-9]{64}$/u,Rm=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var lN=64*1024,uN=64*1024;var fN={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},dN={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function un(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var hN=(1n<<256n)-1n;function Pm(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 Am(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
143
+ `)}function xm(t,e){return B(`comet.native.snapshot-policy.v1
144
+ ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Na(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 Tm(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Uc(t){let e=on(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?Tm(r):void 0;if(a&&!a())return!1;let o=Na(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=Na(i,c,a),o===null||o.size===0)return!1}return Na(i,o,a)?.has(i.length)??!1}}function Im(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>on(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>on(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=xm(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(Uc),excludeMatchers:i.map(Uc),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 q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function V(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function rt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function re(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Qc(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=fn.posix.normalize(t);if(i!==t||fn.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function _m(t,e){let i=q(t,`Native snapshot entry ${e}`);V(i,Nm,`Native snapshot entry ${e}`);let n=Qc(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!dn.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:re(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Rm.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function Om(t,e){let i=q(t,`Native snapshot omission ${e}`);if(V(i,bm,`Native snapshot omission ${e}`),!Em.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Cm.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Qc(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:re(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function jm(t){let e=q(t,"Native snapshot omission overflow");if(V(e,Sm,"Native snapshot omission overflow"),typeof e.hash!="string"||!dn.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:rt(e.count,"Native snapshot omission overflow count")}}function nt(t,e){let i=q(t,e);if(V(i,gm,e),typeof i.hash!="string"||!dn.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=re(i.recordCount,`${e} recordCount`),r=re(i.storedRecordCount,`${e} storedRecordCount`),a=re(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 Yc(t){let e=q(t,"Native Git selection evidence");if(V(e,vm,"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=nt(e.stageBefore,"Native Git selection stageBefore"),n=nt(e.combined,"Native Git selection combined"),r=nt(e.stageAfter,"Native Git selection stageAfter"),a=nt(e.finalStageBefore,"Native Git selection finalStageBefore"),o=nt(e.finalCombined,"Native Git selection finalCombined"),s=nt(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(u=>u.overflow),l=!un(i,r)||!un(r,a)||!un(n,o)||!un(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 Xc(t,e){let i=q(t,e);if(V(i,ym,e),typeof i.hash!="string"||!dn.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=re(i.visitedNodeCount,`${e} visitedNodeCount`),r=re(i.recordCount,`${e} recordCount`),a=re(i.storedRecordCount,`${e} storedRecordCount`),o=re(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 Hm(t){let e=q(t,"Native physical selection evidence");if(V(e,wm,"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=Xc(e.before,"Native physical selection before"),n=Xc(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Pm(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 Zc(t){let e=q(t,"Native content snapshot manifest");if(V(e,fm,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!km.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let v=q(e.capture,"Native content snapshot capture");if(V(v,pm,"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:Yc(v.gitSelection),b=v.physicalSelection===void 0?void 0:Hm(v.physicalSelection),x=null;if(v.projection!==void 0){let M=q(v.projection,"Native content snapshot projection");if(V(M,mm,"Native content snapshot projection"),M.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");x={provider:"git",...M.selection===void 0?{}:{selection:Yc(M.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=q(e.limits,"Native content snapshot limits");V(n,dm,"Native content snapshot limits");let r={maxFiles:rt(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:rt(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:rt(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:rt(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:rt(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let v=q(e.policy,"Native snapshot policy");if(V(v,hm,"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=Im({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(_m),s=e.omitted.map(Om),c=re(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:jm(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>cm||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(Am(E)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function $m(t,e){if(!um.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=fn.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return fn.join(i,"runtime","baseline-manifest.json")}async function el(t,e){let i=$m(t,e);await H(t.nativeRoot,i);try{let n=await zc({root:t.nativeRoot,file:i,maxBytes:lm,label:"Native baseline snapshot manifest"});return Zc(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var ab=256*1024;var wb={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 Tb=16*1024;var Oe="comet.native.v3",je="comet.native.v2",He="comet.native.v1";var il=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Wm=new Set(il),nl=new Set([...il,"minimum_runtime_version","revision"]),Jm=new Set([...nl,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Km=new Set(["capability","operation","source","base_hash"]),Gm=new Set(["shape","build","verify","archive"]),Um=new Set(["implicit","confirmed"]),Ym=new Set(["pending","pass","fail"]),Me="comet-state.yaml",Sa=/^[a-f0-9]{64}$/u,rl=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xm=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,hn=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"},Le=class extends Error{constructor(i,n){super(i!==Oe||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"},pn=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"},mn=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"},Xb=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
145
+ `);function Jt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function al(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 vn(t){if(!rl.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Qm(t){if(!rl.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function ol(t,e){if(t.length===0||$e.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function Zm(t,e){let i=Jt(t,`spec_changes[${e}]`);if(al(i,Km,`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"&&ol(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"||!Sa.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"||!Sa.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 ev(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 Ea(t,e){if(al(t,e,Me),typeof t.name!="string")throw new Error("Native change name is required");if(vn(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"||!Gm.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&&!Um.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(Zm),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"||!Ym.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"&&ol(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!ev(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 Ca(t){let e=Jt(t,Me);if(e.schema!==He)throw new Error(`Expected ${He}`);return{schema:He,...Ea(e,Wm)}}function Wt(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ba(t,e,i){if(t===null)return null;let n=typeof t=="string"?Xm.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 tv(t){if(t==null)return null;if(typeof t!="string"||!Sa.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function iv(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 Ra(t){let e=Jt(t,Me);if(e.schema!==je)throw new Error(`Expected ${je}`);if(Wt(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${je} minimum_runtime_version must be 2`);return{schema:je,minimum_runtime_version:2,revision:Wt(e.revision,"Native v2 revision"),...Ea(e,nl)}}function Pa(t){let e=Jt(t,Me);if(e.schema!==Oe){if(e.schema===He||e.schema===je){let o=e.schema===He?Ca(e):Ra(e);throw new hn(o.name,o.schema)}throw new Le(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=Wt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Le(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=Wt(e.revision,"Native revision"),r=Ea(e,Jm),a=tv(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Oe,minimum_runtime_version:3,revision:n,verification_protocol:iv(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:ba(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ba(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ba(e.partial_allowance,"Native partial_allowance","allowances")}}function nv(t){let e=Jt(t,Me);if(e.schema===He){let r=Ca(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Oe}`}}if(e.schema===je){let r=Ra(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Oe}`}}if(e.schema!==Oe){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 Le(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=Wt(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Le(e.schema,i).message};let n=Pa(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Y(t,e){vn(e);let i=$e.join(t.changesDir,e);if(!ne(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Aa(t,e){let i=$e.join(Y(t,e),"runtime","schema-migration.json");await H(t.nativeRoot,i);try{return await zm.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var rv=256*1024;async function av(t,e=$e.dirname(t)){let i=$e.relative(e,t).split($e.sep).join("/"),n=await xe({root:e,ref:i,maxBytes:rv}),r=(0,ka.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 ov(t,e){let i=$e.join(Y(t,e),Me);await H(t.nativeRoot,i);let n=nv(await av(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Aa(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 sv(t,n.state),n)}async function sv(t,e){if(await el(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function se(t,e){let i=await ov(t,e);if(i.status==="migration-required")throw new hn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Le(i.schema,i.minimumRuntimeVersion);return i.state}import cv from"path";var xa="comet.selection.v2",lv=16*1024;function cl(t){return cv.join(t,".comet","current-change.json")}function uv(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function sl(t){return t===null||typeof t=="string"}function fv(t){let e;try{e=JSON.parse(t)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!uv(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!sl(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:xa,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==xa)throw new Error(`current change selection schema must be ${xa}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!sl(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function ll(t){let e;try{let n=cl(t),{bytes:r}=await Qe(n,lv,{label:"current change selection"});e=r.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...fv(e)}}var lS=16*1024;async function dv(t){let e=await ll(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(vn(e.selection.change),e.selection)}async function ul(t){let e=await dv(t);return e?(await se(t,e.change),e.change):null}function gn(t,e){let i=ot.relative(t,e);return i===""||!i.startsWith("..")&&!ot.isAbsolute(i)}function pv(t,e,i){return i.targets.length>0&&i.targets.every(n=>{let r=ot.resolve(t,n);return gn(t,r)?ot.relative(t,r).replaceAll("\\","/")===".comet/config.yaml"||gn(e,r):!0})}async function mv(t){let e=await tt(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let i=await an(t,e.native.artifact_root),n;try{n=await hv.readdir(i.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:i,changes:[]};throw a}let r=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name))){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=await se(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var vv=Ha("nativeActiveContext",t=>mv(t));async function fl(){let{intent:t,targets:e}=await Ba();return{intent:t,targets:e}}async function dl(t,e,i){let n=await vv(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:pv(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let r;if(i){if(r=n.changes.find(s=>s.name===i),!r)return{allowed:!1,reason:`Selected Native change ${i} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:i}}else if(n.changes.length===1)r=n.changes[0];else{let s=await ul(n.paths);if(r=n.changes.find(c=>c.name===s),!r)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}if(r.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:r.phase,change:r.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!1,reason:`Hook write target could not be determined while Native change ${r.name} is in ${r.phase}; resume /comet-native before retrying`,workflow:"native",phase:r.phase,change:r.name};let a=!1,o=!1;for(let s of e.targets){let c=ot.resolve(t,s);if(!gn(t,c)){o=!0;continue}if(ot.relative(t,c).replaceAll("\\","/")===".comet/config.yaml"||gn(n.paths.nativeRoot,c)){a=!0;continue}return{allowed:!1,reason:`Native change ${r.name} is in ${r.phase}; implementation writes are only allowed in build. Resume /comet-native to continue safely`,workflow:"native",phase:r.phase,change:r.name}}return{allowed:!0,reason:a?"Native control artifact write":o?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:r.phase,change:r.name}}import Xv from"path";var wv=["Outcome","Scope","Non-goals","Acceptance examples"],OS=[...wv,"Constraints and invariants","Decisions","Open questions","Verification expectations"];import{createHash as yv}from"crypto";function X(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Nv(t,e){e.has(t)&&X("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)||X("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&X("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&X("symbol properties are not supported"),`[${t.map(n=>Ta(n,e)).join(",")}]`}finally{e.delete(t)}}function bv(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&X("only plain objects are supported"),e.has(t)&&X("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&X("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))&&X("accessor properties are not supported"),`${JSON.stringify(o)}:${Ta(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Ta(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)||X("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Nv(t,e):bv(t,e);case"bigint":case"function":case"symbol":case"undefined":return X(`${typeof t} values are not supported`)}return X("unsupported value type")}function Ia(t){return Ta(t,new Set)}function Q(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 yv("sha256").update(`${t}
146
+ ${Ia(e)}`).digest("hex")}var Sv=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 hl=1024*1024;var ml="scoped-text-safety",kv=1,Ev=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Cv="comet.native.checker-policy.v1";var XS=Q(Cv,{policy:ml,version:kv,limits:Ev,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Rv=["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"],QS=new Set(Rv);var Av=hl,vk=3*Av;var vl={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:[]},xv=B("comet-native-runtime:v3:semantic-repair-budget"),Wk=[{skillVersion:"2",skillHash:B("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:B("comet-native-runtime:v1")}];var wl=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],CE=new Set(wl),Hv=new Set([...wl,"minimum_runtime_version","revision"]),RE=new Set([...Hv,"operation"]),PE=512*1024,$v=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),AE=new Set([...$v,"implementationScopeHash","repairScopeHash","repairStagnation"]);var IE=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),yl=Object.freeze({maxCriteria:1024});var ME={maxAcceptanceCriteria:yl.maxCriteria};var VE={maxSpecs:64,maxFileBytes:Ki,maxTotalBytes:4*1024*1024};import{execFile as zv,spawn as xC}from"node:child_process";import{promisify as Wv}from"node:util";var eC={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var SC=512*1024;var VC=64*1024;var zC=3600*1e3;var WC=Wv(zv);var JC=["$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 yn=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 _R={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var zR=16*1024*1024,WR=256*1024,JR=16*1024;var OP=16*1024*1024,Nn=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"},bn=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 VP=10*1024*1024,ce=class extends Error{};function bl(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new ce(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Sn(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new ce(`${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 ce(`${e} requires a value`);return t.splice(n,2),r}function Sl(t){if(t.length>0)throw new ce(`Unexpected argument: ${t[0]}`)}async function kl(t){return t?Xv.resolve(t):ma(process.cwd())}function El(t,e){if(e instanceof ce)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Nn)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 bn)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof pn)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 mn)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 yn)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 Cl(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}})+`
147
147
  `}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function Rl(t,e){let i=Sn(t,"--hook-output");if(i!==void 0&&i!=="copilot")throw new ce("--hook-output must be copilot");Sl(t);let n=await dl(e,await fl());return i==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{}
148
148
  `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:n.reason})}
149
- `}:n.allowed?{command:"hook-guard",exitCode:0,data:n}:{command:"hook-guard",exitCode:2,data:n,error:{code:"blocked",message:n.reason}}}function Xv(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}})+`
150
- `}}async function Pl(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{bl(r,"--json"),s=Sn(r,"--project-root");let d=[...r,...a],u=await kl(s);c=await e(d,u)}catch(d){c=El(t,d)}let l=o?Xv(c):Cl(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
149
+ `}:n.allowed?{command:"hook-guard",exitCode:0,data:n}:{command:"hook-guard",exitCode:2,data:n,error:{code:"blocked",message:n.reason}}}function Qv(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}})+`
150
+ `}}async function Pl(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{bl(r,"--json"),s=Sn(r,"--project-root");let d=[...r,...a],u=await kl(s);c=await e(d,u)}catch(d){c=El(t,d)}let l=o?Qv(c):Cl(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
151
151
  `)?"":`
152
152
  `)),l.exitCode}process.exitCode=await Pl("hook-guard",Rl);