@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,8 +139,8 @@ ${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(t){let i=t.items[t.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):t.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)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){hc(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.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>t.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),t.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),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(sn(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(ag(i.key)&&!sn(i.sep,"newline")){let o=Ir(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(sn(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Ir(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?t.items.push({start:a,key:null,sep:[this.sourceToken]}):sn(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?(t.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(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!sn(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&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.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):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){hc(r,i.start),r.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||sn(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.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(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.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?t.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?t.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":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);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===t.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=fc(n),a=Ir(r);rg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
141
141
  `)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
142
- `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=fc(t),n=Ir(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=fc(t),n=Ir(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};og.Parser=ef});var dg=P(Qa=>{"use strict";var sg=qd(),pA=Va(),Xa=Wa(),mA=Fu(),vA=K(),gA=Zd(),cg=tf();function lg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new gA.LineCounter||null,prettyErrors:t}}function wA(e,t={}){let{lineCounter:i,prettyErrors:n}=lg(t),r=new cg.Parser(i?.addNewLine),a=new sg.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(Xa.prettifyError(e,i)),s.warnings.forEach(Xa.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ug(e,t={}){let{lineCounter:i,prettyErrors:n}=lg(t),r=new cg.Parser(i?.addNewLine),a=new sg.Composer(t),o=null;for(let s of a.compose(r.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Xa.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Xa.prettifyError(e,i)),o.warnings.forEach(Xa.prettifyError(e,i))),o}function yA(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=ug(e,i);if(!r)return null;if(r.warnings.forEach(a=>mA.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 NA(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),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(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return vA.isDocument(e)&&!n?e.toString(i):new pA.Document(e,n,i).toString(i)}Qa.parse=yA;Qa.parseAllDocuments=wA;Qa.parseDocument=ug;Qa.stringify=NA});var mc=P(te=>{"use strict";var bA=qd(),SA=Va(),kA=bd(),nf=Wa(),EA=Pa(),cn=K(),RA=nn(),CA=ke(),PA=an(),AA=on(),xA=uc(),TA=Xd(),_A=Zd(),IA=tf(),pc=dg(),fg=ka();te.Composer=bA.Composer;te.Document=SA.Document;te.Schema=kA.Schema;te.YAMLError=nf.YAMLError;te.YAMLParseError=nf.YAMLParseError;te.YAMLWarning=nf.YAMLWarning;te.Alias=EA.Alias;te.isAlias=cn.isAlias;te.isCollection=cn.isCollection;te.isDocument=cn.isDocument;te.isMap=cn.isMap;te.isNode=cn.isNode;te.isPair=cn.isPair;te.isScalar=cn.isScalar;te.isSeq=cn.isSeq;te.Pair=RA.Pair;te.Scalar=CA.Scalar;te.YAMLMap=PA.YAMLMap;te.YAMLSeq=AA.YAMLSeq;te.CST=xA;te.Lexer=TA.Lexer;te.LineCounter=_A.LineCounter;te.Parser=IA.Parser;te.parse=pc.parse;te.parseAllDocuments=pc.parseAllDocuments;te.parseDocument=pc.parseDocument;te.stringify=pc.stringify;te.visit=fg.visit;te.visitAsync=fg.visitAsync});import{pathToFileURL as CD}from"url";import{randomUUID as D$}from"crypto";import{promises as M$}from"fs";import Ei from"path";import{isDeepStrictEqual as F$}from"util";import{createHash as nE}from"crypto";function Sp(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function kp(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))kp(e[t]);return Object.freeze(e)}function Xi(e){return kp(structuredClone(e))}function bu(e,t,i,n){return e.resolveStep({pkg:Xi(t),state:Xi(i),context:Xi(n)})}function Ep(e,t,i,n,r,a){return e.resolveNext({pkg:Xi(t),state:Xi(i),step:Xi(n),outcome:Xi(r),context:Xi(a)})}function rE(e,t,i){return nE("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Su(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function ms(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=bu(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Su(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:rE(s.runId,s.iteration,o.id),stepId:o.id};return aE(e,s,c,i)}function aE(e,t,i,n){let r=Sp(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function vs(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?bu(n,e,t,r):void 0,o=a?Su(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Ep(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Su(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Gf}from"fs";import iy from"path";var _o=Nu(mc(),1);import{promises as ji}from"fs";import gt from"path";import{createHash as HA}from"node:crypto";import{promises as Lt}from"node:fs";import Et from"node:path";import{TextDecoder as DA}from"node:util";import rf from"path";var jA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),OA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function $A(e){return e.toLowerCase().startsWith(".env")}function ai(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>$A(n))?"environment-file":i.some(n=>OA.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>jA.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Za(e,t){let i=ai(t);if(i)return i;let n=rf.resolve(e.projectRoot,...t.split("/")),r=rf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===rf.resolve(e.configFile)?"native-runtime":null}function ln(e){return e!==0&&e!==0n&&e!=="0"}function ze(e,t){return ln(e.dev)&&ln(t.dev)&&ln(e.ino)&&ln(t.ino)}function L(e,t){let i=ln(e.dev)&&ln(t.dev);if(i&&e.dev!==t.dev)return!1;let n=ln(e.ino)&&ln(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var eo=1024*1024;function af(e,t){let i=Et.relative(e,t);return i===""||!Et.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Et.sep}`)}function MA(e){let t=Et.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Et.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=ai(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function FA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function LA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hg(e){let t=await Lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qA(e,t){let i=Et.resolve(e),n=Et.resolve(t);if(!af(i,n))throw new Error("Native artifact path is outside its root");let r=[await hg(i)],a=i;for(let o of Et.relative(i,n).split(Et.sep).filter(Boolean)){a=Et.join(a,o);let s=await hg(a);if(!af(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function pg(e){for(let t of e){let i=await Lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!LA(t,i)||await Lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ge(e){let t=MA(e.ref),i=FA(e.maxBytes??eo),n=Et.resolve(e.root,...t.split("/")),r=await qA(e.root,Et.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Lt.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Lt.realpath(n);if(!af(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Lt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Lt.lstat(n),Lt.realpath(n)]);if(await pg(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!vc(a,c)||!vc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let N=i+1-f,S=await s.read(p,0,Math.min(p.length,N),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Lt.lstat(n),Lt.realpath(n)]);if(await pg(r),!h.isFile()||h.isSymbolicLink()||v!==o||!vc(c,m)||!vc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),E;try{E=new DA("utf-8",{fatal:!0}).decode(b)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:HA("sha256").update(b).digest("hex"),text:E}}finally{await s.close()}}import{randomUUID as BA}from"crypto";import{promises as We}from"fs";import qt from"path";function sf(e,t){let i=qt.relative(e,t);return i===""||!qt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${qt.sep}`)}function VA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function of(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mg(e){let t=await We.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await We.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function to(e){for(let t of e){let i=await We.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!VA(t,i)||await We.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function JA(e,t){let i=qt.resolve(e),n=qt.resolve(t);if(!sf(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await mg(i)],a=qt.relative(i,n).split(qt.sep).filter(Boolean),o=i;for(let s of a){await to(r),o=qt.join(o,s);try{await We.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await mg(o);if(!sf(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await to(r),r}async function zA(e){let t;try{t=await We.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function vg(e,t,i={}){let n=qt.dirname(e),r=i.containedRoot?await JA(i.containedRoot,n):null;r||await We.mkdir(n,{recursive:!0});let a=qt.join(n,`.${qt.basename(e)}.${BA()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await We.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([We.lstat(a),We.realpath(a)]);if(await to(r),!c.isFile()||c.isSymbolicLink()||!of(s,c)||!sf(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!of(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await to(r);let c=await We.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!of(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await We.link(a,e),await We.unlink(a)):await We.rename(a,e),await zA(n)}catch(c){if(await o?.close(),!r)await We.rm(a,{force:!0});else try{await to(r),await We.rm(a,{force:!0})}catch{}throw c}}async function je(e,t,i={}){await vg(e,t,i)}async function gg(e,t,i={}){await vg(e,t,i)}async function de(e,t,i={}){await je(e,JSON.stringify(t,null,2)+`
143
- `,i)}import lx from"path";var no=Nu(mc(),1);import wc from"path";var bc=64*1024,yc=1024,Nc=64,Sc=5,WA=[".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/**"],it={include:["**/*"],exclude:[...WA],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},gc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
142
+ `,i)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=fc(t),n=Ir(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=fc(t),n=Ir(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};og.Parser=ef});var dg=P(Qa=>{"use strict";var sg=qd(),pA=Va(),Xa=Wa(),mA=Fu(),vA=K(),gA=Zd(),cg=tf();function lg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new gA.LineCounter||null,prettyErrors:t}}function wA(e,t={}){let{lineCounter:i,prettyErrors:n}=lg(t),r=new cg.Parser(i?.addNewLine),a=new sg.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(Xa.prettifyError(e,i)),s.warnings.forEach(Xa.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ug(e,t={}){let{lineCounter:i,prettyErrors:n}=lg(t),r=new cg.Parser(i?.addNewLine),a=new sg.Composer(t),o=null;for(let s of a.compose(r.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Xa.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Xa.prettifyError(e,i)),o.warnings.forEach(Xa.prettifyError(e,i))),o}function yA(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=ug(e,i);if(!r)return null;if(r.warnings.forEach(a=>mA.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 NA(e,t,i){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:i===void 0&&t&&(i=t),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(e===void 0){let{keepUndefined:r}=i??t??{};if(!r)return}return vA.isDocument(e)&&!n?e.toString(i):new pA.Document(e,n,i).toString(i)}Qa.parse=yA;Qa.parseAllDocuments=wA;Qa.parseDocument=ug;Qa.stringify=NA});var mc=P(te=>{"use strict";var bA=qd(),SA=Va(),kA=bd(),nf=Wa(),EA=Pa(),cn=K(),RA=nn(),CA=ke(),PA=an(),AA=on(),xA=uc(),TA=Xd(),_A=Zd(),IA=tf(),pc=dg(),fg=ka();te.Composer=bA.Composer;te.Document=SA.Document;te.Schema=kA.Schema;te.YAMLError=nf.YAMLError;te.YAMLParseError=nf.YAMLParseError;te.YAMLWarning=nf.YAMLWarning;te.Alias=EA.Alias;te.isAlias=cn.isAlias;te.isCollection=cn.isCollection;te.isDocument=cn.isDocument;te.isMap=cn.isMap;te.isNode=cn.isNode;te.isPair=cn.isPair;te.isScalar=cn.isScalar;te.isSeq=cn.isSeq;te.Pair=RA.Pair;te.Scalar=CA.Scalar;te.YAMLMap=PA.YAMLMap;te.YAMLSeq=AA.YAMLSeq;te.CST=xA;te.Lexer=TA.Lexer;te.LineCounter=_A.LineCounter;te.Parser=IA.Parser;te.parse=pc.parse;te.parseAllDocuments=pc.parseAllDocuments;te.parseDocument=pc.parseDocument;te.stringify=pc.stringify;te.visit=fg.visit;te.visitAsync=fg.visitAsync});import{pathToFileURL as PD}from"url";import{randomUUID as M$}from"crypto";import{promises as F$}from"fs";import Ei from"path";import{isDeepStrictEqual as L$}from"util";import{createHash as nE}from"crypto";function Sp(e,t,i,n){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!n.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function kp(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))kp(e[t]);return Object.freeze(e)}function Xi(e){return kp(structuredClone(e))}function bu(e,t,i,n){return e.resolveStep({pkg:Xi(t),state:Xi(i),context:Xi(n)})}function Ep(e,t,i,n,r,a){return e.resolveNext({pkg:Xi(t),state:Xi(i),step:Xi(n),outcome:Xi(r),context:Xi(a)})}function rE(e,t,i){return nE("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function Su(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function ms(e,t,i,n,r){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=bu(n,e,t,r);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Su(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:rE(s.runId,s.iteration,o.id),stepId:o.id};return aE(e,s,c,i)}function aE(e,t,i,n){let r=Sp(i,t,e.guardrails,n);return r.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:r.reason}}function vs(e,t,i,n,r){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?bu(n,e,t,r):void 0,o=a?Su(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Ep(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Su(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as Gf}from"fs";import iy from"path";var _o=Nu(mc(),1);import{promises as ji}from"fs";import gt from"path";import{createHash as HA}from"node:crypto";import{promises as Lt}from"node:fs";import Et from"node:path";import{TextDecoder as DA}from"node:util";import rf from"path";var jA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),OA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function $A(e){return e.toLowerCase().startsWith(".env")}function ai(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>$A(n))?"environment-file":i.some(n=>OA.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>jA.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Za(e,t){let i=ai(t);if(i)return i;let n=rf.resolve(e.projectRoot,...t.split("/")),r=rf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===rf.resolve(e.configFile)?"native-runtime":null}function ln(e){return e!==0&&e!==0n&&e!=="0"}function ze(e,t){return ln(e.dev)&&ln(t.dev)&&ln(e.ino)&&ln(t.ino)}function L(e,t){let i=ln(e.dev)&&ln(t.dev);if(i&&e.dev!==t.dev)return!1;let n=ln(e.ino)&&ln(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var eo=1024*1024;function af(e,t){let i=Et.relative(e,t);return i===""||!Et.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Et.sep}`)}function MA(e){let t=Et.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Et.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),n=ai(e);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function FA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function LA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function vc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function hg(e){let t=await Lt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Lt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qA(e,t){let i=Et.resolve(e),n=Et.resolve(t);if(!af(i,n))throw new Error("Native artifact path is outside its root");let r=[await hg(i)],a=i;for(let o of Et.relative(i,n).split(Et.sep).filter(Boolean)){a=Et.join(a,o);let s=await hg(a);if(!af(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function pg(e){for(let t of e){let i=await Lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!LA(t,i)||await Lt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ge(e){let t=MA(e.ref),i=FA(e.maxBytes??eo),n=Et.resolve(e.root,...t.split("/")),r=await qA(e.root,Et.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await Lt.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Lt.realpath(n);if(!af(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Lt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Lt.lstat(n),Lt.realpath(n)]);if(await pg(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!vc(a,c)||!vc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let N=i+1-f,S=await s.read(p,0,Math.min(p.length,N),null);if(S.bytesRead===0)break;if(f+=S.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Lt.lstat(n),Lt.realpath(n)]);if(await pg(r),!h.isFile()||h.isSymbolicLink()||v!==o||!vc(c,m)||!vc(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),E;try{E=new DA("utf-8",{fatal:!0}).decode(b)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:HA("sha256").update(b).digest("hex"),text:E}}finally{await s.close()}}import{randomUUID as BA}from"crypto";import{promises as We}from"fs";import qt from"path";function sf(e,t){let i=qt.relative(e,t);return i===""||!qt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${qt.sep}`)}function VA(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function of(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mg(e){let t=await We.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await We.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function to(e){for(let t of e){let i=await We.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!VA(t,i)||await We.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function JA(e,t){let i=qt.resolve(e),n=qt.resolve(t);if(!sf(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await mg(i)],a=qt.relative(i,n).split(qt.sep).filter(Boolean),o=i;for(let s of a){await to(r),o=qt.join(o,s);try{await We.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await mg(o);if(!sf(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await to(r),r}async function zA(e){let t;try{t=await We.open(e,"r"),await t.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await t?.close()}}async function vg(e,t,i={}){let n=qt.dirname(e),r=i.containedRoot?await JA(i.containedRoot,n):null;r||await We.mkdir(n,{recursive:!0});let a=qt.join(n,`.${qt.basename(e)}.${BA()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await We.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([We.lstat(a),We.realpath(a)]);if(await to(r),!c.isFile()||c.isSymbolicLink()||!of(s,c)||!sf(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!of(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),r){await to(r);let c=await We.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!of(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await We.link(a,e),await We.unlink(a)):await We.rename(a,e),await zA(n)}catch(c){if(await o?.close(),!r)await We.rm(a,{force:!0});else try{await to(r),await We.rm(a,{force:!0})}catch{}throw c}}async function je(e,t,i={}){await vg(e,t,i)}async function gg(e,t,i={}){await vg(e,t,i)}async function de(e,t,i={}){await je(e,JSON.stringify(t,null,2)+`
143
+ `,i)}import ux from"path";var no=Nu(mc(),1);import wc from"path";var bc=64*1024,yc=1024,Nc=64,Sc=5,WA=[".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/**"],it={include:["**/*"],exclude:[...WA],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},gc={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
144
  # ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs, changes, and runtime data.","native.language":`# Artifact language used by Native workflow documents.
145
145
  # language: en | zh-CN`,"native.clarification_mode":`# Controls whether Native asks one clarification at a time or every currently answerable question in a round.
146
146
  # clarification_mode: sequential | batch`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
@@ -161,45 +161,45 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
161
161
  # 可选值:true | false`}};function yg(e,t){return gc[t][e]}function UA(e,t,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let r=n[1].length,a=n[2];if(r===0&&a in gc.en)return a;if(r===2&&t){let o=`${t}.${a}`;if(o in gc.en)return o}if(r===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in gc.en)return o}return null}function kc(e,t){let i=[],n=null,r=null;for(let a of(0,no.stringify)(e).trimEnd().split(`
162
162
  `)){let o=UA(a,n,r);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of yg(o,t).split(`
163
163
  `))i.push(`${s}${c}`)}i.push(a),/^[a-z_]+:/u.test(a)?(a.startsWith("native:")?n="native":a.startsWith("classic:")?n="classic":n=null,r=null):/^ {2}[a-z_]+:/u.test(a)&&n==="native"&&(r=a.startsWith(" snapshot:")?"snapshot":null)}return i.push(""),i.join(`
164
- `)}function KA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||wc.posix.isAbsolute(i)||wc.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function Un(e){let t=KA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ng(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function lf(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||wc.posix.isAbsolute(n)||wc.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function bg(e,t,i){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Ec(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>yc)throw new Error(`${t} exceeds ${yc} characters`);let i=0;for(let n=0;n<e.length;n+=1)e[n]==="?"?i+=1:e[n]==="*"&&(i+=1,e[n+1]==="*"&&(n+=1));if(i>Nc)throw new Error(`${t} contains more than ${Nc} wildcard tokens`);return e}function wg(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>Ec(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function cf(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function GA(e){if(e===void 0)return{...it,include:[...it.include],exclude:[...it.exclude]};let t=io(e,"native.snapshot");return{include:wg(t.include,"native.snapshot.include",it.include),exclude:wg(t.exclude,"native.snapshot.exclude",it.exclude),max_files:cf(t.max_files,it.max_files,"native.snapshot.max_files"),max_total_bytes:cf(t.max_total_bytes,it.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:cf(t.max_duration_ms,it.max_duration_ms,"native.snapshot.max_duration_ms")}}function YA(e){if(e===void 0)return;let t=io(e,"native.pending_root_move"),i=t.id,n=t.from_artifact_root,r=t.to_artifact_root,a=t.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(t.cleanup!==void 0){let s=io(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Un(n),toArtifactRoot:Un(r),stage:a,...o?{cleanup:o}:{}}}function XA(e){let t=io(e,"native");if(typeof t.artifact_root!="string")throw new Error("native.artifact_root must be a string");let i=t.clarification_mode??"sequential";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let n=t.archive_confirmation??"automatic";if(n!=="automatic"&&n!=="required")throw new Error("native.archive_confirmation must be automatic or required");let r=t.max_verify_failures??Sc;if(!Number.isSafeInteger(r)||r<1)throw new Error("native.max_verify_failures must be a positive integer");let a=YA(t.pending_root_move);return{artifact_root:Un(t.artifact_root),language:bg(t.language,"en","native.language"),clarification_mode:i,archive_confirmation:n,max_verify_failures:r,snapshot:GA(t.snapshot),...a?{pending_root_move:a}:{}}}function QA(e){let t=io(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ng(t.artifact_layout),language:bg(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function ZA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ex(e,t,i,n,r){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.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(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:n,...t?{native:t}:{},...i?{classic:i}:{}}}function ro(e,t={}){let i=(0,no.parseDocument)(e,{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=ZA(r.ambient_resume),o=r.native===void 0?void 0:XA(r.native),s=r.classic===void 0?void 0:QA(r.classic),c=ex(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Sg(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function kg(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,snapshot:e.native.snapshot,...e.native.pending_root_move?{pending_root_move:Sg(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function jr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Rc(e,t){let i=kg(t),n=ro((0,no.stringify)(i)).config;if(!n)throw new Error("Unsupported Comet project schema");let r={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.native){let a=jr(e.native),o=jr(a.snapshot),s={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,snapshot:{...o,...n.native.snapshot}};if(n.native.pending_root_move){let c=jr(a.pending_root_move),l=Sg(n.native.pending_root_move),u=jr(c.cleanup),d=jr(l.cleanup);s.pending_root_move={...c,...l,...l.cleanup?{cleanup:{...u,...d}}:{}}}else delete s.pending_root_move;r.native=s}return n.classic&&(r.classic={...jr(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition}),r}function uf(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Un(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Sc,snapshot:{...it,include:[...it.include],exclude:[...it.exclude]}}}}import{createHash as ix}from"crypto";import{promises as Ac}from"fs";import dn from"path";import{constants as Cc,promises as Kn}from"fs";var Rt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function df(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Eg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ao(e){return{dev:e.dev,ino:e.ino,birthtime:df(e)}}function Pc(e,t){let i=ao(e),n=ao(t);return ze(i,n)?L(i,n):L(i,n)&&df(e)===df(t)&&Eg(e)===Eg(t)&&e.size===t.size}async function un(e,t,i={}){if(!Number.isSafeInteger(t)||t<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 Kn.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Rt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Rt("too-large",`${n} exceeds ${t} bytes`);let o=await Kn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:ao(a)});let s=process.platform==="win32"?Cc.O_RDONLY:Cc.O_RDONLY|Cc.O_NOFOLLOW|Cc.O_NONBLOCK,c;try{c=await Kn.open(e,s)}catch(l){throw l.code==="ELOOP"?new Rt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Kn.lstat(e,{bigint:r}),Kn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Pc(a,l)||!Pc(a,u))throw new Rt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:ao(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let E=t+1-p,{bytesRead:N}=await c.read(m,0,Math.min(m.length,E),null);if(N===0)break;if(p+=N,p>t)throw new Rt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([c.stat({bigint:r}),Kn.lstat(e,{bigint:r}),Kn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||b!==o||!Pc(a,h)||!Pc(a,v))throw new Rt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:ao(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:b}}finally{await c.close()}}function tx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ff(e,t){let i=dn.relative(e,t);return i===""||!dn.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${dn.sep}`)}async function Rg(e,t){let i=dn.resolve(e),n=await Ac.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ac.realpath(i)}async function Cg(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=dn.join(r,i[a]);let o;try{o=await Ac.lstat(r)}catch(u){if(tx(u))return{exists:!1,kind:"missing"};throw u}let s=dn.relative(e,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 Ac.realpath(r);if(!ff(t,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 oo(e,t,i){let n=lf(t,i.label),r=dn.resolve(e),a=await Rg(r,i.label),o=n.split("/"),s=dn.resolve(r,...o);if(!ff(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Cg(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Or(e,t,i,n){let r=await oo(e,t,{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 Rg(r.projectRoot,n.label);return un(r.target,i,{...n,verify:async(o,s)=>{if(!ff(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Cg(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var so=".comet/config.yaml";function hf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function nx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function pf(e,t={}){return(await co(e,t)).document}async function Pg(e){try{return(await Or(e,so,bc,{label:so})).bytes}catch(t){if(nx(t))return null;throw t}}function Ag(e){return e?{exists:!0,sha256:ix("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function xc(e){return Ag(await Pg(e))}async function co(e,t={}){let i=await Pg(e);return{document:i?ro(i.toString("utf8"),t):null,identity:Ag(i)}}var HF=16*1024;async function vf(e,t){if(!t)return;let i=await xc(e);if(!hf(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as Gn}from"fs";import se from"path";import ox from"os";var fo=".comet/config.yaml";async function gf(e){try{return await Gn.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function sx(e){try{let t=await Gn.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lo(e,t){let i=se.relative(e,t);return i===""||!se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${se.sep}`)}async function uo(e){let t=[],i=e;for(;!await gf(i);){let r=se.dirname(i);if(r===i)break;t.push(se.basename(i)),i=r}let n=await Gn.realpath(i);return se.resolve(n,...t.reverse())}async function xg(e){try{return(await Gn.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Tc(e){let t=se.resolve(e);try{(await Gn.stat(t)).isDirectory()||(t=se.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=se.resolve(ox.homedir());for(;;){if(!(t===n&&i!==n)){let o=se.join(t,...fo.split("/")),s=t===i||await sx(o);if(await gf(o)&&s)return t}if(await gf(se.join(t,".git")))return t;let a=se.dirname(t);if(a===t)return i;t=a}}function fn(e){return Un(e)}async function cx(e,t){let i=fn(t),n=se.resolve(e,...i.split("/")),r=await Gn.realpath(e),a=await uo(n);if(!lo(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function we(e,t){let i=fn(t),n=await cx(e,i),r=se.join(n,"comet");if(await xg(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([uo(n),uo(r)]);if(!lo(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:se.resolve(e),configFile:se.join(e,...fo.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:se.join(r,"specs"),changesDir:se.join(r,"changes"),archiveDir:se.join(r,"archive"),runtimeDir:se.join(r,"runtime"),locksDir:se.join(r,"runtime","locks"),transactionsDir:se.join(r,"runtime","transactions")}}async function _c(e){let t=[e.specsDir,e.changesDir,e.archiveDir,e.locksDir,e.transactionsDir];await Promise.all(t.map(async i=>{await A(e.nativeRoot,i),await Gn.mkdir(i,{recursive:!0})}))}function $(e,t){return lo(se.resolve(e),se.resolve(t))}async function A(e,t){let i=se.resolve(e),n=se.resolve(t);if(!lo(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await xg(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([uo(i),uo(n)]);if(!lo(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Ic=it,Tg=Sc,jc=Ec;function Yn(e="docs",t="en"){return uf(e,t)}async function le(e){let t=(await pf(e))?.config??null;return t?.native?t:null}async function $r(e){let t=await le(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function oi(e,t,i={}){let n=await co(e,{allowPartialProject:!0}),r=Rc(n.document?.value??{},t),a=lx.join(e,...fo.split("/"));await je(a,kc(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await vf(e,n.identity)}})}async function _g(e){let t=await Tc(e.startPath),i=await le(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${fo} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?fn(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??Yn(n??"docs"),a=await we(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as zx}from"fs";import Wx from"path";import{AsyncLocalStorage as ux}from"async_hooks";import{randomUUID as Og}from"crypto";import{promises as Ct}from"fs";import $g from"os";import pe from"path";var Ig=16*1024,wf=".coordinator",dx=5e3,jg=new ux,Oc=new Map;function fx(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function hx(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Hg(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function yf(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ze(i,n)?L(i,n):L(i,n)&&e.size===t.size}function $c(e,t){return yf(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function px(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&$c(e.identity,t.identity)}async function si(e){let t,i;try{let n=await un(e,Ig,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Rt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Ig} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:hx(JSON.parse(t.toString("utf8")),e),identity:Hg(i)}}async function mx(e){return(await si(e))?.owner??null}function Nf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==$g.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=bx(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function vx(e,t){try{await Ct.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Ct.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Hc(e,t){let i=await si(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!$c(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ct.mkdir(t,{recursive:!0});let n=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${Og()}.removed`);try{await Ct.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await si(n);if(!r||r.owner.id!==e.owner.id||!yf(r.identity,e.identity))throw await vx(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ct.rm(n,{force:!0}),"removed"}function Dg(e){return{id:Og(),pid:process.pid,hostname:$g.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Mg(e,t){let i;try{i=await Ct.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await mx(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
165
- `,"utf8"),await i.sync(),Hg(await i.stat({bigint:!0}))}finally{await i.close()}}async function gx(e,t){let i=await A(e.nativeRoot,e.locksDir);await Ct.mkdir(i,{recursive:!0});let n=await A(e.nativeRoot,pe.join(i,wf));await Ct.mkdir(n,{recursive:!0});let r=Dg(t),a=pe.join(n,`.${r.id}.tmp`),o=pe.join(n,`${r.id}.claim`);try{let s=await Mg(a,r);await Ct.rename(a,o);let c=await si(o);if(!c||!yf(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await Ct.rm(a,{force:!0})}}async function wx(e){let t=pe.dirname(e.file),i=!1,n=pe.basename(e.file);for(let r of await Ct.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=pe.join(t,r.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await si(a),s=Nf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hc(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Fg(e){let t=await si(e.file);if(t){if(t.owner.id!==e.owner.id||!$c(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,pe.dirname(e.file))}}async function yx(e,t){let i=Date.now()+dx;for(;;){let n=await gx(e,t);if(!await wx(n))return n;if(await Fg(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function Nx(e){let t=Oc.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Oc.set(e,r),await t,()=>{i(),Oc.get(e)===r&&Oc.delete(e)}}async function Dc(e,t,i){let n=pe.resolve(e.locksDir),r=jg.getStore();if(r?.has(n))return i();let a=await Nx(n);try{let o=await yx(e,t),s=new Map(r??[]);return s.set(n,o),await jg.run(s,async()=>{try{return await i()}finally{await Fg(o)}})}finally{a()}}async function Mc(e,t,i){let n=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?Dc(o,t,()=>r(a+1)):i()};return r(0)}async function ci(e,t,i){return Dc(e,`acquire ${t}`,async()=>{let n=await A(e.nativeRoot,e.locksDir);await Ct.mkdir(n,{recursive:!0});let r=await A(e.nativeRoot,pe.join(n,fx(t))),a=Dg(i),o=await Mg(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function li(e){await si(e.file)&&await Dc(e,`release ${pe.basename(e.file)}`,async()=>{let t=await si(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!$c(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,wf);await Hc(t,i)})}function bx(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function ho(e){return Nf(await si(e))}async function bf(e,t,i){return Dc(e,`take over ${pe.basename(t)}`,async()=>{let n=await A(e.nativeRoot,e.locksDir),r=await A(e.nativeRoot,t);if(pe.resolve(pe.dirname(r))!==pe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await si(r),o=Nf(a);if(o.status==="missing")return{status:"missing"};if(i&&!px(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(n,wf);return await Hc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as po}from"fs";import Xe from"path";import{TextDecoder as Cx}from"util";import{createHash as Sx}from"node:crypto";import{constants as Fc,promises as J}from"node:fs";import Q from"node:path";import{TextDecoder as kx}from"node:util";function Ue(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function Lg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Dr(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qg(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Hr(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function hn(e,t){let i=await J.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await J.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function pn(e,t,i){let n=Q.resolve(e),r=Q.resolve(t);if(!Ue(n,r))throw new Error(`${i} is outside its managed root`);let a=[await hn(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await ve(a,i),o=Q.join(o,s);let c=await hn(o,i);if(!Ue(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let n=await J.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Dr(i,n)||await J.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Ex(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function ue(e){let t=Lg(e.maxBytes),i=Q.resolve(e.file),n=await pn(e.root,Q.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>hn(Q.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(n,e.label);let a=await J.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=qg(a),s=await J.realpath(i);if(!Ue(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Ue(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Fc.O_RDONLY:Fc.O_RDONLY|Fc.O_NOFOLLOW|Fc.O_NONBLOCK,l=await J.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([J.lstat(i),J.realpath(i)]);if(await ve(n,e.label),await ve(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Hr(o,u)||!Hr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Ex(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),J.lstat(i),J.realpath(i)]);if(await ve(n,e.label),await ve(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Hr(o,m)||!Hr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Sx("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Lc(e){let t=await ue(e),i;try{i=new kx("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:i}}async function pt(e){let t=await pn(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await J.readdir(e.directory,{withFileTypes:!0});else{let n=Lg(e.maxEntries);i=[];let r=await J.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function ui(e){let t=await pn(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function Rx(e){let t=Q.resolve(e.directory),i=Q.resolve(e.quarantine);if(Q.dirname(i)!==Q.dirname(t)||!Ue(Q.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await pn(e.root,Q.dirname(t),e.label),r=await hn(t,e.label);if(!Ue(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(n,e.label);let a=await J.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Dr(r,a)||await J.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await J.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await J.rename(t,i),await ve(n,e.label);let o=await J.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Dr(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await J.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:n,identity:r}}async function Bg(e){await Rx(e)}async function qc(e){let t=Q.resolve(e.file),i=await pn(e.root,Q.dirname(t),e.label),n=await J.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=qg(n),a=await J.realpath(t);if(!Ue(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ue({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([J.lstat(t),J.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Hr(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([J.lstat(t),J.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Hr(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await J.rm(t),await ve(i,e.label)}async function Sf(e){let t=Q.resolve(e.directory),i=await pn(e.root,Q.dirname(t),e.label),n=await hn(t,e.label);if(!Ue(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let r=await J.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Dr(n,r)||await J.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await J.rmdir(t),await ve(i,e.label)}async function di(e){let t=Q.resolve(e.root),i=Q.resolve(e.directory);if(!Ue(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await hn(t,e.label)],r=t;for(let a of Q.relative(t,i).split(Q.sep).filter(Boolean)){await ve(n,e.label),r=Q.join(r,a);try{await J.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await hn(r,e.label);if(!Ue(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await ve(n,e.label)}async function kf(e){let t=Q.resolve(e.root),i=Q.resolve(e.source),n=Q.resolve(e.target);if(i===n||!Ue(t,i)||!Ue(t,n)||Ue(i,n)||Ue(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await di({root:t,directory:Q.dirname(n),label:`${e.label} target parent`});let r=await pn(t,Q.dirname(i),e.label),a=await pn(t,Q.dirname(n),e.label),o=await hn(i,e.label);if(!Ue(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await J.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(r,e.label),ve(a,e.label)]);let s=await J.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Dr(o,s)||await J.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await J.rename(i,n),await Promise.all([ve(r,e.label),ve(a,e.label)]);let c=await J.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Dr(o,c)||!Ue(r[0].realPath,await J.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await J.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ai(e){let t=await ue({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await gg(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await J.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var Px=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Ax=new Set(["id","type","source","target","staged","backup"]),xx=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Tx=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),_x=new Set(["sequence","timestamp","type","operationId"]),Wg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Ug=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),Ix=256*1024,jx=1024*1024,Kg=16*1024,Vc=1024,Cf=64*1024*1024,Ox=2e4,Gg=new Cx("utf-8",{fatal:!0});function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vo(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Fr(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ef(e,t){if(typeof e!="string"||e.length===0||Xe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Bc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Vg(e,t){if(Ef(e,t),e.includes("\\")||e!==Xe.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function $x(e,t){let i=mo(e,`transaction operations[${t}]`);if(vo(i,Ax,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ef(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Ef(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function go(e){let t=mo(e,"Native Archive transaction journal");if(vo(t,xx,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Wg.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Fr(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Bc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=mo(s,`Archive transaction operations[${c}]`);if(vo(l,Tx,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Vg(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Vg(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Bc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Bc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Bc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Pf(e){let t=mo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return go(t);if(vo(t,Px,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Wg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Xe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Xe.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Fr(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map($x),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Yg(e,t){let i=mo(e,`Native transaction event at line ${t}`);if(vo(i,_x,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Fr(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Ug.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function Hx(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;n<e.length;n+=1){let r=t[n],a=e[n];if(r==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==r)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[n,r,a,o]of i){if(e.length<=n)continue;let s=e.slice(n,Math.min(n+r,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Fr(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Fr(e)}function Mr(e,t){return e.length<t.length&&t.startsWith(e)}function Dx(e){let t='","operationId":"';if(Mr(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),n=i.indexOf('"');if(n===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let r=i.slice(0,n);return/^[a-z0-9][a-z0-9-]*$/u.test(r)?Mr(i.slice(n),'"}'):!1}function Mx(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Kg)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Mr(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!Hx(r))return!1;if(n.length<24)return!0;if(!Fr(r))return!1;let a='","type":"',o=n.slice(24);if(Mr(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Ug){if(Mr(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(Dx(l))return!0}else if(Mr(l,'"}'))return!0}return!1}function Fx(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Kg)throw new Error(`Native transaction event at line ${t} is too large`);return Yg(JSON.parse(e),t)}function Lx(e){let t=e.split(`
166
- `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Vc)throw new Error(`Native transaction event log exceeds ${Vc} events`);let n=[];for(let r=0;r<t.length;r+=1){let a=r+1,o=t[r],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&r===t.length-1;try{n.push(Fx(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&Mx(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return n}function Xg(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
164
+ `)}function KA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||wc.posix.isAbsolute(i)||wc.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function Un(e){let t=KA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Ng(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function lf(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||wc.posix.isAbsolute(n)||wc.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function bg(e,t,i){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Ec(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>yc)throw new Error(`${t} exceeds ${yc} characters`);let i=0;for(let n=0;n<e.length;n+=1)e[n]==="?"?i+=1:e[n]==="*"&&(i+=1,e[n+1]==="*"&&(n+=1));if(i>Nc)throw new Error(`${t} contains more than ${Nc} wildcard tokens`);return e}function wg(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>Ec(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function cf(e,t,i){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function GA(e){if(e===void 0)return{...it,include:[...it.include],exclude:[...it.exclude]};let t=io(e,"native.snapshot");return{include:wg(t.include,"native.snapshot.include",it.include),exclude:wg(t.exclude,"native.snapshot.exclude",it.exclude),max_files:cf(t.max_files,it.max_files,"native.snapshot.max_files"),max_total_bytes:cf(t.max_total_bytes,it.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:cf(t.max_duration_ms,it.max_duration_ms,"native.snapshot.max_duration_ms")}}function YA(e){if(e===void 0)return;let t=io(e,"native.pending_root_move"),i=t.id,n=t.from_artifact_root,r=t.to_artifact_root,a=t.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(t.cleanup!==void 0){let s=io(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Un(n),toArtifactRoot:Un(r),stage:a,...o?{cleanup:o}:{}}}function XA(e,t={}){let i=io(e,"native"),n=i.artifact_root??(t.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??Sc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=YA(i.pending_root_move);return{artifact_root:Un(n),language:bg(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:GA(i.snapshot),...s?{pending_root_move:s}:{}}}function QA(e){let t=io(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Ng(t.artifact_layout),language:bg(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function ZA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ex(e,t,i,n,r){let a=e.schema!==void 0;if(!(a||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!a)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=e.workflows??[e.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(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:n,...t?{native:t}:{},...i?{classic:i}:{}}}function ro(e,t={}){let i=(0,no.parseDocument)(e,{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=ZA(r.ambient_resume),o=r.native===void 0?void 0:XA(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:QA(r.classic),c=ex(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Sg(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function kg(e){return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,snapshot:e.native.snapshot,...e.native.pending_root_move?{pending_root_move:Sg(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function jr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Rc(e,t){let i=kg(t),n=ro((0,no.stringify)(i)).config;if(!n)throw new Error("Unsupported Comet project schema");let r={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.native){let a=jr(e.native),o=jr(a.snapshot),s={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,snapshot:{...o,...n.native.snapshot}};if(n.native.pending_root_move){let c=jr(a.pending_root_move),l=Sg(n.native.pending_root_move),u=jr(c.cleanup),d=jr(l.cleanup);s.pending_root_move={...c,...l,...l.cleanup?{cleanup:{...u,...d}}:{}}}else delete s.pending_root_move;r.native=s}return n.classic&&(r.classic={...jr(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition}),r}function uf(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Un(e),language:t,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Sc,snapshot:{...it,include:[...it.include],exclude:[...it.exclude]}}}}import{createHash as ix}from"crypto";import{promises as Ac}from"fs";import dn from"path";import{constants as Cc,promises as Kn}from"fs";var Rt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function df(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Eg(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ao(e){return{dev:e.dev,ino:e.ino,birthtime:df(e)}}function Pc(e,t){let i=ao(e),n=ao(t);return ze(i,n)?L(i,n):L(i,n)&&df(e)===df(t)&&Eg(e)===Eg(t)&&e.size===t.size}async function un(e,t,i={}){if(!Number.isSafeInteger(t)||t<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 Kn.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new Rt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Rt("too-large",`${n} exceeds ${t} bytes`);let o=await Kn.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:ao(a)});let s=process.platform==="win32"?Cc.O_RDONLY:Cc.O_RDONLY|Cc.O_NOFOLLOW|Cc.O_NONBLOCK,c;try{c=await Kn.open(e,s)}catch(l){throw l.code==="ELOOP"?new Rt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),Kn.lstat(e,{bigint:r}),Kn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Pc(a,l)||!Pc(a,u))throw new Rt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:ao(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let E=t+1-p,{bytesRead:N}=await c.read(m,0,Math.min(m.length,E),null);if(N===0)break;if(p+=N,p>t)throw new Rt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,N)))}await i.hooks?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([c.stat({bigint:r}),Kn.lstat(e,{bigint:r}),Kn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||b!==o||!Pc(a,h)||!Pc(a,v))throw new Rt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:ao(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:b}}finally{await c.close()}}function tx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ff(e,t){let i=dn.relative(e,t);return i===""||!dn.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${dn.sep}`)}async function Rg(e,t){let i=dn.resolve(e),n=await Ac.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ac.realpath(i)}async function Cg(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=dn.join(r,i[a]);let o;try{o=await Ac.lstat(r)}catch(u){if(tx(u))return{exists:!1,kind:"missing"};throw u}let s=dn.relative(e,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 Ac.realpath(r);if(!ff(t,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 oo(e,t,i){let n=lf(t,i.label),r=dn.resolve(e),a=await Rg(r,i.label),o=n.split("/"),s=dn.resolve(r,...o);if(!ff(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Cg(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Or(e,t,i,n){let r=await oo(e,t,{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 Rg(r.projectRoot,n.label);return un(r.target,i,{...n,verify:async(o,s)=>{if(!ff(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Cg(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var so=".comet/config.yaml";function hf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function nx(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function pf(e,t={}){return(await co(e,t)).document}async function Pg(e){try{return(await Or(e,so,bc,{label:so})).bytes}catch(t){if(nx(t))return null;throw t}}function Ag(e){return e?{exists:!0,sha256:ix("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function xc(e){return Ag(await Pg(e))}async function co(e,t={}){let i=await Pg(e);return{document:i?ro(i.toString("utf8"),t):null,identity:Ag(i)}}var DF=16*1024;async function vf(e,t){if(!t)return;let i=await xc(e);if(!hf(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as Gn}from"fs";import se from"path";import sx from"os";var fo=".comet/config.yaml";async function gf(e){try{return await Gn.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function cx(e){try{let t=await Gn.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lo(e,t){let i=se.relative(e,t);return i===""||!se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${se.sep}`)}async function uo(e){let t=[],i=e;for(;!await gf(i);){let r=se.dirname(i);if(r===i)break;t.push(se.basename(i)),i=r}let n=await Gn.realpath(i);return se.resolve(n,...t.reverse())}async function xg(e){try{return(await Gn.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Tc(e){let t=se.resolve(e);try{(await Gn.stat(t)).isDirectory()||(t=se.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=se.resolve(sx.homedir());for(;;){if(!(t===n&&i!==n)){let o=se.join(t,...fo.split("/")),s=t===i||await cx(o);if(await gf(o)&&s)return t}if(await gf(se.join(t,".git")))return t;let a=se.dirname(t);if(a===t)return i;t=a}}function fn(e){return Un(e)}async function lx(e,t){let i=fn(t),n=se.resolve(e,...i.split("/")),r=await Gn.realpath(e),a=await uo(n);if(!lo(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function we(e,t){let i=fn(t),n=await lx(e,i),r=se.join(n,"comet");if(await xg(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([uo(n),uo(r)]);if(!lo(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:se.resolve(e),configFile:se.join(e,...fo.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:se.join(r,"specs"),changesDir:se.join(r,"changes"),archiveDir:se.join(r,"archive"),runtimeDir:se.join(r,"runtime"),locksDir:se.join(r,"runtime","locks"),transactionsDir:se.join(r,"runtime","transactions")}}async function _c(e){let t=[e.specsDir,e.changesDir,e.archiveDir,e.locksDir,e.transactionsDir];await Promise.all(t.map(async i=>{await A(e.nativeRoot,i),await Gn.mkdir(i,{recursive:!0})}))}function $(e,t){return lo(se.resolve(e),se.resolve(t))}async function A(e,t){let i=se.resolve(e),n=se.resolve(t);if(!lo(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await xg(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([uo(i),uo(n)]);if(!lo(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var Ic=it,Tg=Sc,jc=Ec;function Yn(e="docs",t="en"){return uf(e,t)}async function le(e){let t=(await pf(e))?.config??null;return t?.native?t:null}async function $r(e){let t=await le(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function oi(e,t,i={}){let n=await co(e,{allowPartialProject:!0}),r=Rc(n.document?.value??{},t),a=ux.join(e,...fo.split("/"));await je(a,kc(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await vf(e,n.identity)}})}async function _g(e){let t=await Tc(e.startPath),i=await le(t);if(!i&&e.allowMissingConfig===!1)throw new Error(`${fo} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=e.explicitArtifactRoot?fn(e.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??Yn(n??"docs"),a=await we(t,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as Wx}from"fs";import Ux from"path";import{AsyncLocalStorage as dx}from"async_hooks";import{randomUUID as Og}from"crypto";import{promises as Ct}from"fs";import $g from"os";import pe from"path";var Ig=16*1024,wf=".coordinator",fx=5e3,jg=new dx,Oc=new Map;function hx(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function px(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function Hg(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function yf(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ze(i,n)?L(i,n):L(i,n)&&e.size===t.size}function $c(e,t){return yf(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function mx(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&$c(e.identity,t.identity)}async function si(e){let t,i;try{let n=await un(e,Ig,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Rt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Ig} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:px(JSON.parse(t.toString("utf8")),e),identity:Hg(i)}}async function vx(e){return(await si(e))?.owner??null}function Nf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==$g.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Sx(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function gx(e,t){try{await Ct.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Ct.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function Hc(e,t){let i=await si(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!$c(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ct.mkdir(t,{recursive:!0});let n=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${Og()}.removed`);try{await Ct.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await si(n);if(!r||r.owner.id!==e.owner.id||!yf(r.identity,e.identity))throw await gx(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ct.rm(n,{force:!0}),"removed"}function Dg(e){return{id:Og(),pid:process.pid,hostname:$g.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Mg(e,t){let i;try{i=await Ct.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await vx(e);throw new Error(`Native lock is already held: ${e}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(t,null,2)+`
165
+ `,"utf8"),await i.sync(),Hg(await i.stat({bigint:!0}))}finally{await i.close()}}async function wx(e,t){let i=await A(e.nativeRoot,e.locksDir);await Ct.mkdir(i,{recursive:!0});let n=await A(e.nativeRoot,pe.join(i,wf));await Ct.mkdir(n,{recursive:!0});let r=Dg(t),a=pe.join(n,`.${r.id}.tmp`),o=pe.join(n,`${r.id}.claim`);try{let s=await Mg(a,r);await Ct.rename(a,o);let c=await si(o);if(!c||!yf(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await Ct.rm(a,{force:!0})}}async function yx(e){let t=pe.dirname(e.file),i=!1,n=pe.basename(e.file);for(let r of await Ct.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=pe.join(t,r.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await si(a),s=Nf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hc(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function Fg(e){let t=await si(e.file);if(t){if(t.owner.id!==e.owner.id||!$c(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,pe.dirname(e.file))}}async function Nx(e,t){let i=Date.now()+fx;for(;;){let n=await wx(e,t);if(!await yx(n))return n;if(await Fg(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function bx(e){let t=Oc.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return Oc.set(e,r),await t,()=>{i(),Oc.get(e)===r&&Oc.delete(e)}}async function Dc(e,t,i){let n=pe.resolve(e.locksDir),r=jg.getStore();if(r?.has(n))return i();let a=await bx(n);try{let o=await Nx(e,t),s=new Map(r??[]);return s.set(n,o),await jg.run(s,async()=>{try{return await i()}finally{await Fg(o)}})}finally{a()}}async function Mc(e,t,i){let n=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?Dc(o,t,()=>r(a+1)):i()};return r(0)}async function ci(e,t,i){return Dc(e,`acquire ${t}`,async()=>{let n=await A(e.nativeRoot,e.locksDir);await Ct.mkdir(n,{recursive:!0});let r=await A(e.nativeRoot,pe.join(n,hx(t))),a=Dg(i),o=await Mg(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function li(e){await si(e.file)&&await Dc(e,`release ${pe.basename(e.file)}`,async()=>{let t=await si(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!$c(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,wf);await Hc(t,i)})}function Sx(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function ho(e){return Nf(await si(e))}async function bf(e,t,i){return Dc(e,`take over ${pe.basename(t)}`,async()=>{let n=await A(e.nativeRoot,e.locksDir),r=await A(e.nativeRoot,t);if(pe.resolve(pe.dirname(r))!==pe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await si(r),o=Nf(a);if(o.status==="missing")return{status:"missing"};if(i&&!mx(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(n,wf);return await Hc(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as po}from"fs";import Xe from"path";import{TextDecoder as Px}from"util";import{createHash as kx}from"node:crypto";import{constants as Fc,promises as J}from"node:fs";import Q from"node:path";import{TextDecoder as Ex}from"node:util";function Ue(e,t){let i=Q.relative(e,t);return i===""||!Q.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Q.sep}`)}function Lg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Dr(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qg(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Hr(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function hn(e,t){let i=await J.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await J.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function pn(e,t,i){let n=Q.resolve(e),r=Q.resolve(t);if(!Ue(n,r))throw new Error(`${i} is outside its managed root`);let a=[await hn(n,i)],o=n;for(let s of Q.relative(n,r).split(Q.sep).filter(Boolean)){await ve(a,i),o=Q.join(o,s);let c=await hn(o,i);if(!Ue(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ve(a,i),a}async function ve(e,t){for(let i of e){let n=await J.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Dr(i,n)||await J.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function Rx(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function ue(e){let t=Lg(e.maxBytes),i=Q.resolve(e.file),n=await pn(e.root,Q.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>hn(Q.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ve(n,e.label);let a=await J.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=qg(a),s=await J.realpath(i);if(!Ue(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Ue(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Fc.O_RDONLY:Fc.O_RDONLY|Fc.O_NOFOLLOW|Fc.O_NONBLOCK,l=await J.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([J.lstat(i),J.realpath(i)]);if(await ve(n,e.label),await ve(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Hr(o,u)||!Hr(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Rx(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),J.lstat(i),J.realpath(i)]);if(await ve(n,e.label),await ve(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Hr(o,m)||!Hr(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:kx("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Lc(e){let t=await ue(e),i;try{i=new Ex("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:i}}async function pt(e){let t=await pn(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await J.readdir(e.directory,{withFileTypes:!0});else{let n=Lg(e.maxEntries);i=[];let r=await J.opendir(e.directory);try{for await(let a of r)if(i.push(a),i.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await r.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ve(t,e.label),{entries:i,verify:()=>ve(t,e.label)}}async function ui(e){let t=await pn(e.root,e.directory,e.label);return{verify:()=>ve(t,e.label)}}async function Cx(e){let t=Q.resolve(e.directory),i=Q.resolve(e.quarantine);if(Q.dirname(i)!==Q.dirname(t)||!Ue(Q.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await pn(e.root,Q.dirname(t),e.label),r=await hn(t,e.label);if(!Ue(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ve(n,e.label);let a=await J.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Dr(r,a)||await J.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await J.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await J.rename(t,i),await ve(n,e.label);let o=await J.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Dr(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await J.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:n,identity:r}}async function Bg(e){await Cx(e)}async function qc(e){let t=Q.resolve(e.file),i=await pn(e.root,Q.dirname(t),e.label),n=await J.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=qg(n),a=await J.realpath(t);if(!Ue(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ue({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([J.lstat(t),J.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Hr(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ve(i,e.label);let[l,u]=await Promise.all([J.lstat(t),J.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Hr(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await J.rm(t),await ve(i,e.label)}async function Sf(e){let t=Q.resolve(e.directory),i=await pn(e.root,Q.dirname(t),e.label),n=await hn(t,e.label);if(!Ue(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ve(i,e.label);let r=await J.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Dr(n,r)||await J.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await J.rmdir(t),await ve(i,e.label)}async function di(e){let t=Q.resolve(e.root),i=Q.resolve(e.directory);if(!Ue(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await hn(t,e.label)],r=t;for(let a of Q.relative(t,i).split(Q.sep).filter(Boolean)){await ve(n,e.label),r=Q.join(r,a);try{await J.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await hn(r,e.label);if(!Ue(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await ve(n,e.label)}async function kf(e){let t=Q.resolve(e.root),i=Q.resolve(e.source),n=Q.resolve(e.target);if(i===n||!Ue(t,i)||!Ue(t,n)||Ue(i,n)||Ue(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await di({root:t,directory:Q.dirname(n),label:`${e.label} target parent`});let r=await pn(t,Q.dirname(i),e.label),a=await pn(t,Q.dirname(n),e.label),o=await hn(i,e.label);if(!Ue(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await J.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ve(r,e.label),ve(a,e.label)]);let s=await J.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Dr(o,s)||await J.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await J.rename(i,n),await Promise.all([ve(r,e.label),ve(a,e.label)]);let c=await J.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Dr(o,c)||!Ue(r[0].realPath,await J.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await J.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ai(e){let t=await ue({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await gg(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await J.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ue({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var Ax=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),xx=new Set(["id","type","source","target","staged","backup"]),Tx=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),_x=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Ix=new Set(["sequence","timestamp","type","operationId"]),Wg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Ug=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),jx=256*1024,Ox=1024*1024,Kg=16*1024,Vc=1024,Cf=64*1024*1024,$x=2e4,Gg=new Px("utf-8",{fatal:!0});function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vo(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Fr(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ef(e,t){if(typeof e!="string"||e.length===0||Xe.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Bc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Vg(e,t){if(Ef(e,t),e.includes("\\")||e!==Xe.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function Hx(e,t){let i=mo(e,`transaction operations[${t}]`);if(vo(i,xx,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ef(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Ef(i[n],`transaction operation ${i.id} ${n}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function go(e){let t=mo(e,"Native Archive transaction journal");if(vo(t,Tx,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Wg.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Fr(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Bc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=mo(s,`Archive transaction operations[${c}]`);if(vo(l,_x,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Vg(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Vg(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Bc(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Bc(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Bc(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=i.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let r=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${r}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${r}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function Pf(e){let t=mo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return go(t);if(vo(t,Ax,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Wg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Xe.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Xe.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Fr(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(Hx),n=i.map(r=>r.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Yg(e,t){let i=mo(e,`Native transaction event at line ${t}`);if(vo(i,Ix,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Fr(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Ug.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let n=i.type==="operation-started"||i.type==="operation-completed";if(n&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!n&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function Dx(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let n=0;n<e.length;n+=1){let r=t[n],a=e[n];if(r==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==r)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[n,r,a,o]of i){if(e.length<=n)continue;let s=e.slice(n,Math.min(n+r,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(r,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Fr(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Fr(e)}function Mr(e,t){return e.length<t.length&&t.startsWith(e)}function Mx(e){let t='","operationId":"';if(Mr(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),n=i.indexOf('"');if(n===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let r=i.slice(0,n);return/^[a-z0-9][a-z0-9-]*$/u.test(r)?Mr(i.slice(n),'"}'):!1}function Fx(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Kg)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Mr(e,i))return!0;if(!e.startsWith(i))return!1;let n=e.slice(i.length),r=n.slice(0,Math.min(24,n.length));if(!Dx(r))return!1;if(n.length<24)return!0;if(!Fr(r))return!1;let a='","type":"',o=n.slice(24);if(Mr(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Ug){if(Mr(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(Mx(l))return!0}else if(Mr(l,'"}'))return!0}return!1}function Lx(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Kg)throw new Error(`Native transaction event at line ${t} is too large`);return Yg(JSON.parse(e),t)}function qx(e){let t=e.split(`
166
+ `),i=t.at(-1)==="";if(i&&t.pop(),t.length>Vc)throw new Error(`Native transaction event log exceeds ${Vc} events`);let n=[];for(let r=0;r<t.length;r+=1){let a=r+1,o=t[r],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&r===t.length-1;try{n.push(Lx(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&Fx(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return n}function Xg(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
167
167
  `)}
168
- `}function qx(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Xe.join(e.transactionsDir,t)}function zc(e,t){let i=qx(e,t);return{directory:i,journal:Xe.join(i,"transaction.json"),events:Xe.join(i,"events.jsonl"),staged:Xe.join(i,"staged"),backups:Xe.join(i,"backups")}}async function Pt(e,t){let i=zc(e,t);return await Promise.all(Object.values(i).map(n=>A(e.nativeRoot,n))),i}function Bx(e,t){if(t.length===0||Xe.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=Xe.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!$(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function mn(e,t){return A(e.nativeRoot,Bx(e,t))}async function Xn(e){try{return await po.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Af(e,t,i={}){let n=await Pt(e,t);try{await po.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await ue({root:e.nativeRoot,file:n.events,maxBytes:jx,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=Gg.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=Lx(a),s=Xg(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function Jg(e,t,i){let n=await Af(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function mt(e,t,i,n){let r=await Pt(e,t),a=await Af(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await je(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>Jg(e,t,a)}),o;if(a.events.length>=Vc)throw new Error(`Native transaction event log ${t} exceeds ${Vc} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return Yg(s,s.sequence),await po.mkdir(r.directory,{recursive:!0}),await je(r.events,Xg([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>Jg(e,t,a)}),s}async function xf(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Pf(t);let i=await Pt(e,t.id);await po.mkdir(i.staged,{recursive:!0}),await po.mkdir(i.backups,{recursive:!0}),await de(i.journal,t),await mt(e,t.id,"prepared")}async function nt(e,t,i={}){let n=await Pt(e,t),r=await ue({root:e.nativeRoot,file:n.journal,maxBytes:Ix,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Gg.decode(r.bytes)),o=Pf(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function vn(e,t,i={}){return(await Af(e,t,i)).events}async function Jc(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=Pf({...t,status:i});return await de((await Pt(e,t.id)).journal,n),n}async function Rf(e,t,i){try{return await ue({root:e.nativeRoot,file:t,maxBytes:Cf,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Tf(e,t,i,n){let r=await Rf(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await Rf(e,i,`${n} target`);await di({root:e.nativeRoot,directory:Xe.dirname(i),label:`${n} target parent`}),await Ai({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:Cf,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Qg(e,t,i){let n=await Rf(e,t,i);n&&await qc({root:e.nativeRoot,file:t,maxBytes:Cf,expectedHash:n.hash,expectedSize:n.size,label:i})}async function zg(e,t){if(!t.backup)return;let i=await mn(e,t.target),n=await mn(e,t.backup);!await Xn(i)||await Xn(n)||await Tf(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function Vx(e,t){let i=await mn(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await zg(e,t),await Tf(e,await mn(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await zg(e,t),await Qg(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await mn(e,t.source),[r,a]=await Promise.all([Xn(n),Xn(i)]);if(!r&&a){await(await pt({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:Ox})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await kf({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function Zg(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await Jc(e,t,"applying"):t,r=await vn(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await mt(e,n.id,"operation-started",s.id),await Vx(e,s),await mt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await nt(e,n.id),n}async function Jx(e,t){let i=await mn(e,t.target),n=t.backup?await mn(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await mn(e,t.source);if(await Xn(i)){if(await Xn(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await kf({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await Xn(n)?await Tf(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await Qg(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Wc(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await vn(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Jc(e,t,"rolling-back");await mt(e,n.id,"rollback-started");let r=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...n.operations].reverse())r.has(a.id)&&await Jx(e,a);return await mt(e,n.id,"rollback-completed"),n=await Jc(e,n,"rolled-back"),n}async function Lr(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await mt(e,t.id,i),i==="commit"?Jc(e,t,"committed"):t}function xi(e,t){let i=Xe.resolve(t);if(!$(e.nativeRoot,i))throw new Error(`Path is outside the Native root: ${t}`);return Xe.relative(e.nativeRoot,i).split(Xe.sep).join("/")}async function Ux(e,t){let i;try{i=await zx.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await nt(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function Kx(e,t){let i=Date.now()+5e3,n=Wx.join(e.locksDir,"root-move.lock");for(;;)try{return await ci(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await ho(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function re(e,t,i,n){let r=await Kx(e,t);try{if(await $r(e.projectRoot),await Ux(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await li(r)}}function ew(e){return Number.isSafeInteger(e)&&e>=1}async function tw(e){if(!ew(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!ew(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Qc}from"crypto";import{spawn as dw}from"node:child_process";import{promises as fe}from"fs";import Z from"path";import{createHash as iw}from"crypto";import{createReadStream as Gx}from"fs";async function rt(e){let t=iw("sha256");for await(let i of Gx(e))t.update(i);return t.digest("hex")}function F(e){return iw("sha256").update(e).digest("hex")}var Uc={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Df=1e3,Yx=8*1024*1024,Xx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qx=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Zx=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),eT=new Set(["schema","include","exclude","hash"]),tT=new Set(["provider","gitSelection","physicalSelection","projection"]),iT=new Set(["provider","selection"]),nT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),rT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),aT=new Set(["schema","status","before","after"]),oT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),sT=new Set(["path","hash","size","type","gitObjectId"]),cT=new Set(["path","size","type","reason"]),lT=new Set(["ref","hash","count"]),uT=new Set(["change-created","legacy-migration","explicit"]),dT=new Set(["file","directory","other"]),fT=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"]),Zc=/^[a-f0-9]{64}$/u,fw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,hT=new Set(["EACCES","EPERM"]),Vr=64*1024,Of=64*1024,pT=6e4,mT=1e3,vT=2,Mf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},gT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function hw(e){let t=e.deadlineMs??pT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Bt(e){return Math.max(0,e.deadlineAt-Date.now())}function q(e){return Bt(e)>=1}function _f(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function No(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function wT(e){let t={...gT,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function yT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&Z.win32.isAbsolute(n)?Z.win32.resolve(n):"C:\\Windows",a=Z.win32.join(r,"System32","taskkill.exe");if(!Z.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=dw(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),mT),u.unref()}catch{d(!1)}});for(let s=0;s<vT;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}e.kill("SIGKILL")}function Ff(e,t,i,n){let r=Bt(e);if(r<1)throw _f();let a=e.gitProcess,o=dw(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[n?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=yT(o,a).then(()=>({error:null}),p=>({error:p}))},r);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let m=await l;throw m?.error?_f(m.error):_f()}return{code:p,spawnError:s}});return{child:o,completion:f}}function pw(e){let t={...Mf,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Gc(e,t,i,n=Of){let{child:r,completion:a}=Ff(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",p=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>n&&(u=!0)}),r.stderr.on("data",p=>{if(c>=Vr)return;let m=Vr-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function If(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Kc(e,t,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=Ff(e,t,i,n.stdin!==void 0),c=[],l=Qc("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,b=!1,E=!1,N=S=>{let R=0;for(;R<S.byteLength;){let w=S.indexOf(0,R),y=w<0?S.byteLength:w,g=S.subarray(R,y);if(!v&&g.byteLength>0&&(h.byteLength+g.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,b=!0):h=Buffer.concat([h,g])),w<0)break;m+=1,h.byteLength===0&&!v&&(E=!0);let k=h.byteLength+1;!v&&m<=n.maxRecords&&p+k<=n.maxBytes?(c.push(h),p+=k):b=!0,h=Buffer.alloc(0),v=!1,R=w+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>n.maxBytes&&(b=!0);let R=n.outputChunkBytes;if(R===void 0){N(S);return}for(let w=0;w<S.byteLength;w+=R)N(S.subarray(w,Math.min(S.byteLength,w+R)))}),o.stderr.on("data",S=>{if(d>=Vr)return;let R=Vr-d,w=Buffer.from(S).subarray(0,R);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:R})=>{let w=n.acceptedExitCodes??[0];if(S!==null&&w.includes(S)&&R===null&&!E&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:b,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:E||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function $f(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function NT(e,t,i){if(i.length===0)return new Set;let n=await Kc(e,t,["check-ignore","--no-index","-z","--stdin"],{...Mf,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(n.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(n.records.map(r=>{let a=$f(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function bT(e,t,i){let{child:n,completion:r}=Ff(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=Vr)return;let d=Vr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Yc(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||Z.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||Z.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function ST(e,t){return e.map(i=>{let n=Yc(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function kT(e){let t=Z.resolve(e);for(;;){try{return await fe.lstat(Z.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=Z.dirname(t);if(i===t)return!1;t=i}}async function mw(e,t,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await Kc(e,t,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await Kc(e,t,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await Kc(e,t,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function vw(e){return{stageBefore:If(e.stagedBefore),combined:If(e.combined),stageAfter:If(e.stagedAfter)}}async function gw(e,t,i=Mf,n={}){if(!await kT(t))return null;let r;try{r=await Gc(e,t,["rev-parse","--is-inside-work-tree"])}catch(b){throw No(b)?b:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:b})}if(r.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let a;try{a=await mw(e,t,i,n)}catch(b){throw No(b)?b:new Error("Native Git snapshot provider failed after repository detection",{cause:b})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,d=new Set,f=b=>{for(let E of b){let N=$f(E),S=N.indexOf(" ");if(S<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let R=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,S))?.groups;if(!R)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Yc(N.slice(S+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(w),R.stage==="0"&&u.set(w,R.objectId),R.mode==="160000"&&R.stage==="0"&&d.add(w)}};f(o.records),f(c.records);let p=s.records.map($f),m=ST(p,"combined"),h=new Set(m.filter(b=>!l.has(b))),v=new Set(m.filter((b,E)=>!l.has(b)&&p[E].endsWith("/")));for(let b of d)v.delete(b);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:d,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:vw(a)}}function wn(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function nw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function ET(e,t){return!wn(e.stageBefore,e.stageAfter)||!wn(e.stageAfter,t.stageBefore)||!wn(e.combined,t.combined)||!wn(t.stageBefore,t.stageAfter)}async function ww(e,t,i,n,r){let a;try{a=await mw(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw No(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=vw(a),c=nw(o)||nw(s),l=ET(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2
169
- ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var RT=(1n<<256n)-1n;function CT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function rw(e){let t=Z.resolve(e.paths.projectRoot),i=Z.resolve(e.paths.nativeRoot),n=Z.resolve(e.paths.configFile),r=Z.join(t,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,d=0,f=!1,p=!1,m=!1,h=()=>Bt(e.execution)>=1?!0:(f=!0,m=!0,!1),v=N=>{let S=Buffer.from(`${N.type}\0${N.path}`,"utf8"),R=Qc("sha256").update("comet.native.physical-selection-record.v1\0").update(S).digest();for(let w=0;w<s.length;w+=1)s[w]^=R[w];if(c=c+BigInt(`0x${R.toString("hex")}`)&RT,u+=1,d+=S.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(N)},b=async N=>{if(m||!h())return;let S;try{S=await fe.opendir(N)}catch(k){if(!h())return;if(!Re(k)&&!Ee(k)||N===t&&Re(k))throw k;p||=Ee(k),f||=Re(k),m=!0;return}if(!h()){try{await S.close()}catch(k){if(k.code!=="ERR_DIR_CLOSED")throw k}return}let R=!1,w;try{for(;!m&&h();){let k;try{k=await S.read()}catch(ne){if(!h())break;if(!Re(ne)&&!Ee(ne)||N===t&&Re(ne))throw ne;p||=Ee(ne),f||=Re(ne),m=!0;break}if(!h()||k===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let x=Z.join(N,k.name),U=AT(t,x);if(x===n||x===r||yn(i,x)||e.denylist.some(ne=>yn(ne,x))||ai(U)!==null)continue;if(!h())break;let D;try{D=await fe.lstat(x)}catch(ne){if(!h())break;if(!Re(ne)&&!Ee(ne))throw ne;if(p=!0,v({path:U,type:"other"}),o.push({path:U,size:null,type:"file",reason:Re(ne)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(U),m||!h())break;continue}if(!h())break;let z=CT(D);if(z==="directory"){if(IT(e.policy,U))continue;if(!h())break;let ne;try{ne=await fe.realpath(x)}catch(ti){if(!h())break;if(!Re(ti)&&!Ee(ti))throw ti;if(p=!0,v({path:U,type:z}),o.push({path:U,size:null,type:"directory",reason:Re(ti)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(U),m||!h())break;continue}if(!h())break;if(!$(e.physicalProjectRoot,ne)||yn(e.physicalNativeRoot,ne))continue;if(v({path:U,type:z}),await e.hooks?.afterNode?.(U),!h()||(await b(x),m))break;continue}if(v({path:U,type:z}),await e.hooks?.afterNode?.(U),!h()||m)break}}catch(k){R=!0,w=k}let y;try{await S.close()}catch(k){y=k}let g=h();if(R)throw w;if(g&&y!==void 0&&y.code!=="ERR_DIR_CLOSED")throw y};await b(t),h(),f?(a.length=0,u=0,d=0):(a.sort((N,S)=>N.path.localeCompare(S.path,"en")),o.sort((N,S)=>N.path.localeCompare(S.path,"en")));let E=f?F(`comet.native.physical-selection-incomplete.v1
168
+ `}function Bx(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Xe.join(e.transactionsDir,t)}function zc(e,t){let i=Bx(e,t);return{directory:i,journal:Xe.join(i,"transaction.json"),events:Xe.join(i,"events.jsonl"),staged:Xe.join(i,"staged"),backups:Xe.join(i,"backups")}}async function Pt(e,t){let i=zc(e,t);return await Promise.all(Object.values(i).map(n=>A(e.nativeRoot,n))),i}function Vx(e,t){if(t.length===0||Xe.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=Xe.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!$(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function mn(e,t){return A(e.nativeRoot,Vx(e,t))}async function Xn(e){try{return await po.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Af(e,t,i={}){let n=await Pt(e,t);try{await po.lstat(n.events)}catch(r){if(r.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw r}try{let r=await ue({root:e.nativeRoot,file:n.events,maxBytes:Ox,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=Gg.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=qx(a),s=Xg(o);return{exists:!0,hash:r.hash,size:r.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:r}):r}}async function Jg(e,t,i){let n=await Af(e,t);if(n.exists!==i.exists||n.hash!==i.hash||n.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function mt(e,t,i,n){let r=await Pt(e,t),a=await Af(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await je(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>Jg(e,t,a)}),o;if(a.events.length>=Vc)throw new Error(`Native transaction event log ${t} exceeds ${Vc} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return Yg(s,s.sequence),await po.mkdir(r.directory,{recursive:!0}),await je(r.events,Xg([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>Jg(e,t,a)}),s}async function xf(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Pf(t);let i=await Pt(e,t.id);await po.mkdir(i.staged,{recursive:!0}),await po.mkdir(i.backups,{recursive:!0}),await de(i.journal,t),await mt(e,t.id,"prepared")}async function nt(e,t,i={}){let n=await Pt(e,t),r=await ue({root:e.nativeRoot,file:n.journal,maxBytes:jx,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Gg.decode(r.bytes)),o=Pf(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function vn(e,t,i={}){return(await Af(e,t,i)).events}async function Jc(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=Pf({...t,status:i});return await de((await Pt(e,t.id)).journal,n),n}async function Rf(e,t,i){try{return await ue({root:e.nativeRoot,file:t,maxBytes:Cf,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Tf(e,t,i,n){let r=await Rf(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await Rf(e,i,`${n} target`);await di({root:e.nativeRoot,directory:Xe.dirname(i),label:`${n} target parent`}),await Ai({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:Cf,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Qg(e,t,i){let n=await Rf(e,t,i);n&&await qc({root:e.nativeRoot,file:t,maxBytes:Cf,expectedHash:n.hash,expectedSize:n.size,label:i})}async function zg(e,t){if(!t.backup)return;let i=await mn(e,t.target),n=await mn(e,t.backup);!await Xn(i)||await Xn(n)||await Tf(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function Jx(e,t){let i=await mn(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await zg(e,t),await Tf(e,await mn(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await zg(e,t),await Qg(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await mn(e,t.source),[r,a]=await Promise.all([Xn(n),Xn(i)]);if(!r&&a){await(await pt({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:$x})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!r)throw new Error(`Move source does not exist: ${t.source}`);await kf({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function Zg(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let n=t.status==="prepared"?await Jc(e,t,"applying"):t,r=await vn(e,t.id),a=new Set(r.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of n.operations)a.has(s.id)||(await mt(e,n.id,"operation-started",s.id),await Jx(e,s),await mt(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await nt(e,n.id),n}async function zx(e,t){let i=await mn(e,t.target),n=t.backup?await mn(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await mn(e,t.source);if(await Xn(i)){if(await Xn(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await kf({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await Xn(n)?await Tf(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await Qg(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Wc(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await vn(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await Jc(e,t,"rolling-back");await mt(e,n.id,"rollback-started");let r=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...n.operations].reverse())r.has(a.id)&&await zx(e,a);return await mt(e,n.id,"rollback-completed"),n=await Jc(e,n,"rolled-back"),n}async function Lr(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await mt(e,t.id,i),i==="commit"?Jc(e,t,"committed"):t}function xi(e,t){let i=Xe.resolve(t);if(!$(e.nativeRoot,i))throw new Error(`Path is outside the Native root: ${t}`);return Xe.relative(e.nativeRoot,i).split(Xe.sep).join("/")}async function Kx(e,t){let i;try{i=await Wx.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let r=await nt(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function Gx(e,t){let i=Date.now()+5e3,n=Ux.join(e.locksDir,"root-move.lock");for(;;)try{return await ci(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await ho(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw r;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function re(e,t,i,n){let r=await Gx(e,t);try{if(await $r(e.projectRoot),await Kx(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await li(r)}}function ew(e){return Number.isSafeInteger(e)&&e>=1}async function tw(e){if(!ew(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!ew(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Qc}from"crypto";import{spawn as dw}from"node:child_process";import{promises as fe}from"fs";import Z from"path";import{createHash as iw}from"crypto";import{createReadStream as Yx}from"fs";async function rt(e){let t=iw("sha256");for await(let i of Yx(e))t.update(i);return t.digest("hex")}function F(e){return iw("sha256").update(e).digest("hex")}var Uc={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Df=1e3,Xx=8*1024*1024,Qx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zx=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),eT=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),tT=new Set(["schema","include","exclude","hash"]),iT=new Set(["provider","gitSelection","physicalSelection","projection"]),nT=new Set(["provider","selection"]),rT=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),aT=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),oT=new Set(["schema","status","before","after"]),sT=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),cT=new Set(["path","hash","size","type","gitObjectId"]),lT=new Set(["path","size","type","reason"]),uT=new Set(["ref","hash","count"]),dT=new Set(["change-created","legacy-migration","explicit"]),fT=new Set(["file","directory","other"]),hT=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"]),Zc=/^[a-f0-9]{64}$/u,fw=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,pT=new Set(["EACCES","EPERM"]),Vr=64*1024,Of=64*1024,mT=6e4,vT=1e3,gT=2,Mf={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},wT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function hw(e){let t=e.deadlineMs??mT;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Bt(e){return Math.max(0,e.deadlineAt-Date.now())}function q(e){return Bt(e)>=1}function _f(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function No(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function yT(e){let t={...wT,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function NT(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&Z.win32.isAbsolute(n)?Z.win32.resolve(n):"C:\\Windows",a=Z.win32.join(r,"System32","taskkill.exe");if(!Z.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=dw(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),vT),u.unref()}catch{d(!1)}});for(let s=0;s<gT;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}e.kill("SIGKILL")}function Ff(e,t,i,n){let r=Bt(e);if(r<1)throw _f();let a=e.gitProcess,o=dw(a.command,[...a.argsPrefix??[],"-C",t,...i],{stdio:[n?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=NT(o,a).then(()=>({error:null}),p=>({error:p}))},r);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let m=await l;throw m?.error?_f(m.error):_f()}return{code:p,spawnError:s}});return{child:o,completion:f}}function pw(e){let t={...Mf,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Gc(e,t,i,n=Of){let{child:r,completion:a}=Ff(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;r.stdout.on("data",p=>{let m=Math.max(0,n-l);m>0&&o.push(Buffer.from(p).subarray(0,m)),l+=p.byteLength,l>n&&(u=!0)}),r.stderr.on("data",p=>{if(c>=Vr)return;let m=Vr-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function If(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Kc(e,t,i,n){if(n.outputChunkBytes!==void 0&&(!Number.isSafeInteger(n.outputChunkBytes)||n.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((r,a)=>{let{child:o,completion:s}=Ff(e,t,i,n.stdin!==void 0),c=[],l=Qc("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,b=!1,E=!1,N=S=>{let R=0;for(;R<S.byteLength;){let w=S.indexOf(0,R),y=w<0?S.byteLength:w,g=S.subarray(R,y);if(!v&&g.byteLength>0&&(h.byteLength+g.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,b=!0):h=Buffer.concat([h,g])),w<0)break;m+=1,h.byteLength===0&&!v&&(E=!0);let k=h.byteLength+1;!v&&m<=n.maxRecords&&p+k<=n.maxBytes?(c.push(h),p+=k):b=!0,h=Buffer.alloc(0),v=!1,R=w+1}};o.stdout.on("data",S=>{l.update(S),f+=S.byteLength,f>n.maxBytes&&(b=!0);let R=n.outputChunkBytes;if(R===void 0){N(S);return}for(let w=0;w<S.byteLength;w+=R)N(S.subarray(w,Math.min(S.byteLength,w+R)))}),o.stderr.on("data",S=>{if(d>=Vr)return;let R=Vr-d,w=Buffer.from(S).subarray(0,R);u.push(w),d+=w.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:S,spawnError:R})=>{let w=n.acceptedExitCodes??[0];if(S!==null&&w.includes(S)&&R===null&&!E&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:b,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:E||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function $f(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function bT(e,t,i){if(i.length===0)return new Set;let n=await Kc(e,t,["check-ignore","--no-index","-z","--stdin"],{...Mf,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(n.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(n.records.map(r=>{let a=$f(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function ST(e,t,i){let{child:n,completion:r}=Ff(e,t,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=Vr)return;let d=Vr-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await r;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Yc(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||Z.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||Z.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function kT(e,t){return e.map(i=>{let n=Yc(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function ET(e){let t=Z.resolve(e);for(;;){try{return await fe.lstat(Z.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=Z.dirname(t);if(i===t)return!1;t=i}}async function mw(e,t,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await Kc(e,t,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await Kc(e,t,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await Kc(e,t,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function vw(e){return{stageBefore:If(e.stagedBefore),combined:If(e.combined),stageAfter:If(e.stagedAfter)}}async function gw(e,t,i=Mf,n={}){if(!await ET(t))return null;let r;try{r=await Gc(e,t,["rev-parse","--is-inside-work-tree"])}catch(b){throw No(b)?b:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:b})}if(r.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let a;try{a=await mw(e,t,i,n)}catch(b){throw No(b)?b:new Error("Native Git snapshot provider failed after repository detection",{cause:b})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,d=new Set,f=b=>{for(let E of b){let N=$f(E),S=N.indexOf(" ");if(S<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let R=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,S))?.groups;if(!R)throw new Error("Native Git snapshot provider returned a malformed staged header");let w=Yc(N.slice(S+1));if(w===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(w),R.stage==="0"&&u.set(w,R.objectId),R.mode==="160000"&&R.stage==="0"&&d.add(w)}};f(o.records),f(c.records);let p=s.records.map($f),m=kT(p,"combined"),h=new Set(m.filter(b=>!l.has(b))),v=new Set(m.filter((b,E)=>!l.has(b)&&p[E].endsWith("/")));for(let b of d)v.delete(b);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:d,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:vw(a)}}function wn(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function nw(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function RT(e,t){return!wn(e.stageBefore,e.stageAfter)||!wn(e.stageAfter,t.stageBefore)||!wn(e.combined,t.combined)||!wn(t.stageBefore,t.stageAfter)}async function ww(e,t,i,n,r){let a;try{a=await mw(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw No(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=vw(a),c=nw(o)||nw(s),l=RT(o,s);c&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&n.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),n.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(n.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2
169
+ ${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var CT=(1n<<256n)-1n;function PT(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function rw(e){let t=Z.resolve(e.paths.projectRoot),i=Z.resolve(e.paths.nativeRoot),n=Z.resolve(e.paths.configFile),r=Z.join(t,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,d=0,f=!1,p=!1,m=!1,h=()=>Bt(e.execution)>=1?!0:(f=!0,m=!0,!1),v=N=>{let S=Buffer.from(`${N.type}\0${N.path}`,"utf8"),R=Qc("sha256").update("comet.native.physical-selection-record.v1\0").update(S).digest();for(let w=0;w<s.length;w+=1)s[w]^=R[w];if(c=c+BigInt(`0x${R.toString("hex")}`)&CT,u+=1,d+=S.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(N)},b=async N=>{if(m||!h())return;let S;try{S=await fe.opendir(N)}catch(k){if(!h())return;if(!Re(k)&&!Ee(k)||N===t&&Re(k))throw k;p||=Ee(k),f||=Re(k),m=!0;return}if(!h()){try{await S.close()}catch(k){if(k.code!=="ERR_DIR_CLOSED")throw k}return}let R=!1,w;try{for(;!m&&h();){let k;try{k=await S.read()}catch(ne){if(!h())break;if(!Re(ne)&&!Ee(ne)||N===t&&Re(ne))throw ne;p||=Ee(ne),f||=Re(ne),m=!0;break}if(!h()||k===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let x=Z.join(N,k.name),U=xT(t,x);if(x===n||x===r||yn(i,x)||e.denylist.some(ne=>yn(ne,x))||ai(U)!==null)continue;if(!h())break;let D;try{D=await fe.lstat(x)}catch(ne){if(!h())break;if(!Re(ne)&&!Ee(ne))throw ne;if(p=!0,v({path:U,type:"other"}),o.push({path:U,size:null,type:"file",reason:Re(ne)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(U),m||!h())break;continue}if(!h())break;let z=PT(D);if(z==="directory"){if(jT(e.policy,U))continue;if(!h())break;let ne;try{ne=await fe.realpath(x)}catch(ti){if(!h())break;if(!Re(ti)&&!Ee(ti))throw ti;if(p=!0,v({path:U,type:z}),o.push({path:U,size:null,type:"directory",reason:Re(ti)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(U),m||!h())break;continue}if(!h())break;if(!$(e.physicalProjectRoot,ne)||yn(e.physicalNativeRoot,ne))continue;if(v({path:U,type:z}),await e.hooks?.afterNode?.(U),!h()||(await b(x),m))break;continue}if(v({path:U,type:z}),await e.hooks?.afterNode?.(U),!h()||m)break}}catch(k){R=!0,w=k}let y;try{await S.close()}catch(k){y=k}let g=h();if(R)throw w;if(g&&y!==void 0&&y.code!=="ERR_DIR_CLOSED")throw y};await b(t),h(),f?(a.length=0,u=0,d=0):(a.sort((N,S)=>N.path.localeCompare(S.path,"en")),o.sort((N,S)=>N.path.localeCompare(S.path,"en")));let E=f?F(`comet.native.physical-selection-incomplete.v1
170
170
  ${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):F(`comet.native.physical-selection.v1
171
- ${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:d,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:E,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function yw(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function PT(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!yw(e,t),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Nw(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function aw(e,t){let n=(await Gc(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!fw.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${n}`)}async function ow(e,t){let i=await aw(e,t),n=await bT(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await aw(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function wo(e,t){if(ai(t)!==null)return!1;let i=Z.resolve(e.projectRoot,...t.split("/"));return!yn(Z.resolve(e.nativeRoot),i)}function el(e,t={}){let i=Ti(e),n=t.maxRecordedPaths??20;if(!Number.isSafeInteger(n)||n<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let r=i.omitted.slice(0,n).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:r,sampleTruncated:r.length<i.omittedCount}}function AT(e,t){return Z.relative(e,t).split(Z.sep).join("/")}function xT(e,t){return t.map(i=>Z.resolve(e,...i.split(/[\\/]/u)))}function yn(e,t){let i=Z.resolve(e),n=Z.resolve(t);return n===i||$(i,n)}function Re(e){return hT.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Lf(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
172
- `)}function TT(e,t){return F(`comet.native.snapshot-policy.v1
173
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function jf(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[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 _T(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function sw(e){let t=jc(e,"Native snapshot pattern"),i=[];for(let n=0;n<t.length;n+=1){let r=t[n];r==="*"&&t[n+1]==="*"?(n+=1,t[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?_T(r):void 0;if(a&&!a())return!1;let o=jf(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 u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=jf(i,c,a),o===null||o.size===0)return!1}return jf(i,o,a)?.has(i.length)??!1}}function bw(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>jc(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>jc(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=TT(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(sw),excludeMatchers:i.map(sw),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 IT(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function cw(e,t,i){if(!e)return!0;let n=()=>q(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function yo(e,t,i){let n=JSON.stringify(i);return F(`${e}
171
+ ${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:d,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:E,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function yw(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function AT(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!yw(e,t),r=[];return i&&r.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),n&&r.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:r,evidence:i||n?{schema:"comet.native.physical-selection.v1",status:i&&n?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function Nw(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function aw(e,t){let n=(await Gc(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!fw.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${n}`)}async function ow(e,t){let i=await aw(e,t),n=await ST(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await aw(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function wo(e,t){if(ai(t)!==null)return!1;let i=Z.resolve(e.projectRoot,...t.split("/"));return!yn(Z.resolve(e.nativeRoot),i)}function el(e,t={}){let i=Ti(e),n=t.maxRecordedPaths??20;if(!Number.isSafeInteger(n)||n<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let r=i.omitted.slice(0,n).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:r,sampleTruncated:r.length<i.omittedCount}}function xT(e,t){return Z.relative(e,t).split(Z.sep).join("/")}function TT(e,t){return t.map(i=>Z.resolve(e,...i.split(/[\\/]/u)))}function yn(e,t){let i=Z.resolve(e),n=Z.resolve(t);return n===i||$(i,n)}function Re(e){return pT.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Lf(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
172
+ `)}function _T(e,t){return F(`comet.native.snapshot-policy.v1
173
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function jf(e,t,i){let n=new Set(t),r=[...t];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=e[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 IT(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function sw(e){let t=jc(e,"Native snapshot pattern"),i=[];for(let n=0;n<t.length;n+=1){let r=t[n];r==="*"&&t[n+1]==="*"?(n+=1,t[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?IT(r):void 0;if(a&&!a())return!1;let o=jf(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 u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=jf(i,c,a),o===null||o.size===0)return!1}return jf(i,o,a)?.has(i.length)??!1}}function bw(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>jc(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>jc(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=_T(t,i);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:n},includeMatchers:t.map(sw),excludeMatchers:i.map(sw),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 jT(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function cw(e,t,i){if(!e)return!0;let n=()=>q(i),r=!1;for(let a of e.includeMatchers){if(!n())return!1;if(a(t,n)){r=!0;break}}if(!r)return!1;for(let a of e.excludeMatchers)if(!n()||a(t,n))return!1;return!0}function yo(e,t,i){let n=JSON.stringify(i);return F(`${e}
174
174
  ${Buffer.byteLength(t)}:${t}
175
- ${Buffer.byteLength(n)}:${n}`)}function Hf(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Xc(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Hf(i))return e.splice(t,1),i}return null}function gn(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function jT(e,t,i,n){if(!q(n))return{status:"budget-exhausted"};let r;try{r=await fe.open(e,"r")}catch(c){if(!q(n))return{status:"budget-exhausted"};throw c}if(!q(n))return await r.close(),{status:"budget-exhausted"};let a=Qc("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!q(n))return{status:"budget-exhausted"};let c=await r.stat();if(!q(n))return{status:"budget-exhausted"};if(!c.isFile()||!gn(i,c))return{status:"changed"};for(;;){if(!q(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!q(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!q(n))return{status:"budget-exhausted"};let d=await r.stat();return q(n)?!d.isFile()||!gn(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function At(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xt(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Br(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Sw(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=Z.posix.normalize(e);if(i!==e||Z.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function OT(e,t){let i=At(e,`Native snapshot entry ${t}`);xt(i,sT,`Native snapshot entry ${t}`);let n=Sw(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Zc.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let r={path:n,hash:i.hash,size:fi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!fw.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function $T(e,t){let i=At(e,`Native snapshot omission ${t}`);if(xt(i,cT,`Native snapshot omission ${t}`),!dT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!fT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Sw(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:fi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function HT(e){let t=At(e,"Native snapshot omission overflow");if(xt(t,lT,"Native snapshot omission overflow"),typeof t.hash!="string"||!Zc.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Br(t.count,"Native snapshot omission overflow count")}}function qr(e,t){let i=At(e,t);if(xt(i,rT,t),typeof i.hash!="string"||!Zc.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=fi(i.recordCount,`${t} recordCount`),r=fi(i.storedRecordCount,`${t} storedRecordCount`),a=fi(i.stdoutBytes,`${t} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function lw(e){let t=At(e,"Native Git selection evidence");if(xt(t,nT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=qr(t.stageBefore,"Native Git selection stageBefore"),n=qr(t.combined,"Native Git selection combined"),r=qr(t.stageAfter,"Native Git selection stageAfter"),a=qr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=qr(t.finalCombined,"Native Git selection finalCombined"),s=qr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!wn(i,r)||!wn(r,a)||!wn(n,o)||!wn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function uw(e,t){let i=At(e,t);if(xt(i,oT,t),typeof i.hash!="string"||!Zc.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=fi(i.visitedNodeCount,`${t} visitedNodeCount`),r=fi(i.recordCount,`${t} recordCount`),a=fi(i.storedRecordCount,`${t} storedRecordCount`),o=fi(i.encodedBytes,`${t} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function DT(e){let t=At(e,"Native physical selection evidence");if(xt(t,aT,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=uw(t.before,"Native physical selection before"),n=uw(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!yw(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(t.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 Ti(e){let t=At(e,"Native content snapshot manifest");if(xt(t,Qx,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!uT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let w=At(t.capture,"Native content snapshot capture");if(xt(w,tT,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let y=w.gitSelection===void 0?void 0:lw(w.gitSelection),g=w.physicalSelection===void 0?void 0:DT(w.physicalSelection),k=null;if(w.projection!==void 0){let x=At(w.projection,"Native content snapshot projection");if(xt(x,iT,"Native content snapshot projection"),x.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");k={provider:"git",...x.selection===void 0?{}:{selection:lw(x.selection)}}}if(w.provider==="git"){if(g||k)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...y?{gitSelection:y}:{}}}else{if(y)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&k)throw new Error("Native physical-tree capture cannot combine selection and projection");i=k?{provider:"physical-tree",projection:k}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=At(t.limits,"Native content snapshot limits");xt(n,Zx,"Native content snapshot limits");let r={maxFiles:Br(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Br(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Br(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Br(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Br(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=At(t.policy,"Native snapshot policy");if(xt(w,eT,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=bw({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(OT),s=t.omitted.map($T),c=fi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:HT(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>r.maxFileBytes)||o.reduce((w,y)=>w+y.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Df||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),b=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...b])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let E=i?.physicalSelection,N=E?.status==="overflow"||E?.status==="overflow-and-changed",S=E?.status==="changed"||E?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let R={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Lf(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function Nn(e,t,i={}){let n=Ti(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=Z.resolve(e.projectRoot),a=hw(i),o=pw(i.gitSelectionLimits),s=await gw(a,r,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Nw(s).filter(g=>wo(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>wo(e,g)),d=(g,k)=>k.some(x=>g===x||g.startsWith(`${x}/`)),f=g=>d(g,l),p=g=>d(g,u),m=[...n.entries.map(g=>g.path),...n.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await NT(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!p(g.path)&&wo(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await ww(a,r,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let g of l)b.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,k)=>g.path.localeCompare(k.path,"en"));let E=n.omitted.filter(g=>f(g.path)||p(g.path)||!wo(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(k=>k.startsWith(`${g.path}/`)):!0);for(let g of b)E.some(k=>k.path===g.path&&k.reason===g.reason)||E.push(g);E.sort((g,k)=>g.path.localeCompare(k.path,"en"));let N=n.omissionOverflow?.count??0,S=n.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,S=yo(S,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{N+=1,S=yo(S,"omission",g)};for(;E.length>Df;){let g=Xc(E);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let w=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:E.length+N===0,entries:v,omitted:E,omittedCount:E.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:N}}:{}}),y=w();for(;Lf(y)>n.limits.maxManifestBytes;){let g=Xc(E);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),y=w()}return Ti(y)}function kw(e,t){if(!Xx.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Z.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return Z.join(i,"runtime","baseline-manifest.json")}async function bo(e,t={}){let i={maxFiles:t.limits?.maxFiles??Uc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Uc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Uc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Uc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=bw(t.policy),r=hw({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=pw(t.gitSelectionLimits),o=wT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=Z.resolve(e.projectRoot),c=await fe.realpath(s),l=Z.resolve(e.nativeRoot),u=await fe.realpath(l),d=Z.resolve(e.configFile),f=Z.join(s,".comet","current-change.json"),p=xT(s,t.denylist??[]),m=[],h=[],v=new Map,b=new Map,E=0,N=0,S=F("comet.native.snapshot-omission-overflow.v1"),R=0,w=!1,y=null,g=T=>{N+=1,S=yo(S,"omission",T)},k=T=>{if(E+=1,h.length<Df){h.push(T);return}if(Hf(T)){let _=Xc(h);if(_===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(_),h.push(T);return}g(T)},x=T=>{E+=T.count,N+=T.count,S=yo(S,"git-selection",{source:"git-selection",...T})},U=T=>{N+=1,S=yo(S,"manifest-entry",{reason:"manifest-size",entry:T})},D=async(T,_)=>{m.push(T),R+=T.size,v.set(T.path,_),w||(w=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(T.path))},z=(T,_)=>{let O=m.findIndex(me=>me.path===T);if(O<0)return;let[V]=m.splice(O,1);R-=V.size,v.delete(T),k(_)},ne=async(T,_,O,V)=>{if(!O.isFile()||O.isSymbolicLink()||!q(r))return;let me;try{me=await fe.realpath(T)}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;k({path:_,size:O.size,type:"file",reason:Ee(M)?"changed-during-read":"unreadable"});return}if(!q(r)||!$(c,me)||yn(u,me))return;if(m.length>=i.maxFiles){k({path:_,size:O.size,type:"file",reason:"file-count"});return}if(O.size>i.maxFileBytes){k({path:_,size:O.size,type:"file",reason:"file-size"});return}if(R+O.size>i.maxTotalBytes){k({path:_,size:O.size,type:"file",reason:"total-size"});return}let Y,B,I;try{if(Y=await jT(me,O.size,O,r),Y.status==="budget-exhausted"||!q(r))return;if(Y.status==="changed"){k({path:_,size:null,type:"file",reason:"changed-during-read"});return}if(!q(r)||(I=await fe.realpath(T),!q(r)))return;B=await fe.lstat(T)}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;k({path:_,size:O.size,type:"file",reason:Ee(M)?"changed-during-read":"unreadable"});return}if(q(r)){if(Y.bytes!==O.size||I!==me||!gn(O,Y.finalStat)||!gn(Y.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==O.size||B.mtimeMs!==O.mtimeMs||B.ctimeMs!==O.ctimeMs){k({path:_,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}q(r)&&await D({path:_,hash:Y.hash,size:B.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:T,realTarget:me,stat:B})}},ti=async(T,_,O)=>{if(!q(r))return;let V,me,Y;try{if(V=await fe.readlink(T,{encoding:"buffer"}),!q(r)||(Y=await fe.lstat(T),!q(r)))return;me=await fe.readlink(T,{encoding:"buffer"})}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;k({path:_,size:null,type:"other",reason:Ee(M)?"changed-during-read":"unreadable"});return}if(!q(r))return;if(!Y.isSymbolicLink()||!gn(O,Y)||Y.mtimeMs!==O.mtimeMs||Y.ctimeMs!==O.ctimeMs||!V.equals(me)){k({path:_,size:null,type:"other",reason:"changed-during-read"});return}let B=V.byteLength;if(m.length>=i.maxFiles){k({path:_,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){k({path:_,size:B,type:"other",reason:"file-size"});return}if(R+B>i.maxTotalBytes){k({path:_,size:B,type:"other",reason:"total-size"});return}let I=Qc("sha256").update("symlink\0").update(V).digest("hex");q(r)&&await D({path:_,hash:I,size:B,type:"file"},{kind:"symlink",target:T,rawTarget:V,stat:Y})},ii=async()=>{for(let[T,_]of[...v]){if(!q(r))return;if(_.kind==="file"){let B,I;try{if(B=await fe.realpath(_.target),!q(r))return;I=await fe.lstat(_.target)}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;z(T,{path:T,size:null,type:"file",reason:Re(M)?"unreadable":"changed-during-read"});continue}if(!q(r))return;(B!==_.realTarget||!I.isFile()||I.isSymbolicLink()||!gn(_.stat,I)||I.size!==_.stat.size||I.mtimeMs!==_.stat.mtimeMs||I.ctimeMs!==_.stat.ctimeMs)&&z(T,{path:T,size:I.isFile()?I.size:null,type:I.isFile()?"file":"other",reason:"changed-during-read"});continue}if(_.kind==="symlink"){let B,I;try{if(B=await fe.lstat(_.target),!q(r))return;I=await fe.readlink(_.target,{encoding:"buffer"})}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;z(T,{path:T,size:null,type:"other",reason:Re(M)?"unreadable":"changed-during-read"});continue}if(!q(r))return;(!B.isSymbolicLink()||!gn(_.stat,B)||B.mtimeMs!==_.stat.mtimeMs||B.ctimeMs!==_.stat.ctimeMs||!_.rawTarget.equals(I))&&z(T,{path:T,size:null,type:"other",reason:"changed-during-read"});continue}let O,V;try{if(O=await fe.realpath(_.target),!q(r))return;V=await fe.lstat(_.target)}catch{if(!q(r))return;z(T,{path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!q(r))return;if(!(O===_.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&gn(_.stat,V)&&$(c,O)&&!yn(u,O))){z(T,{path:T,size:null,type:"directory",reason:"gitlink-changed"});continue}let Y;try{if(!q(r))return;Y=await ow(r,O)}catch(B){if(No(B))throw B;z(T,{path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!q(r))return;Y.dirty?z(T,{path:T,size:null,type:"directory",reason:"gitlink-dirty"}):Y.hash!==_.hash&&z(T,{path:T,size:null,type:"directory",reason:"gitlink-changed"})}for(let[T,_]of b){if(!q(r))return;try{let O=await fe.lstat(_);if(!q(r))return;k({path:T,size:O.isFile()?O.size:null,type:O.isFile()?"file":O.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(O){if(!q(r))return;if(Ee(O))continue;if(!Re(O))throw O;k({path:T,size:null,type:"file",reason:"unreadable"})}}},dt=await gw(r,s,a,t.gitSelectionHooks);if(dt===null){let T=await rw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of T.records){if(V.type!=="file"&&V.type!=="symlink"||v.has(V.path))continue;if(Bt(r)<1)break;if(!cw(n,V.path,r))continue;if(Bt(r)<1)break;let me=Z.resolve(s,...V.path.split("/")),Y;try{Y=await fe.lstat(me)}catch(B){if(!q(r))break;if(!Re(B)&&!Ee(B))throw B;k({path:V.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(Bt(r)<1)break;if(V.type==="symlink"&&Y.isSymbolicLink()){if(await ti(me,V.path,Y),Bt(r)<1)break;continue}if(V.type!=="file"||!Y.isFile()||Y.isSymbolicLink()){k({path:V.path,size:Y.isFile()?Y.size:null,type:Y.isDirectory()?"directory":Y.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ne(me,V.path,Y),Bt(r)<1)break}Bt(r)>=1&&await ii();let _=await rw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),O=PT(T.evidence,_.evidence);y=O.evidence;for(let V of[...T.omissions,..._.omissions,...O.omissions])h.some(me=>me.path===V.path&&me.reason===V.reason)||k(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let T=t.incrementalBaseline,_=new Map,O=!1;if(T){let I=Ti(T);for(let M of I.entries)M.gitObjectId!==void 0&&_.set(M.path,M);O=_.size>0}let V=new Set,me=!0;try{let I=await Gc(r,s,["ls-files","--modified","-z"],Of);for(let M of I.toString("utf8").split("\0")){let Ie=Yc(M);Ie!==null&&V.add(Ie)}}catch{O=!1,me=!1,_.clear()}let Y=new Set,B=new Set;for(let I of Nw(dt)){if(v.has(I)||!wo(e,I))continue;if(Bt(r)<1)break;if(!cw(n,I,r))continue;if(Bt(r)<1)break;let M=Z.resolve(s,...I.split("/"));if(M===d||M===f||p.some(ht=>yn(ht,M)))continue;if(dt.gitlinks.has(I)){if(m.length>=i.maxFiles){k({path:I,size:0,type:"file",reason:"file-count"});continue}let ht,hs;try{[ht,hs]=await Promise.all([fe.realpath(M),fe.lstat(M)])}catch{k({path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(hs.isSymbolicLink()||!hs.isDirectory()||!$(c,ht)||yn(u,ht)){k({path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let br=await ow(r,ht);if(br.dirty){k({path:I,size:null,type:"directory",reason:"gitlink-dirty"});continue}await D({path:I,hash:br.hash,size:0,type:"file"},{kind:"gitlink",target:M,realTarget:ht,stat:hs,hash:br.hash})}catch(br){if(No(br))throw br;k({path:I,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let Ie;try{Ie=await fe.lstat(M)}catch(ht){if(Ee(ht)&&dt.tracked.has(I)){b.set(I,M);continue}if(!Re(ht)&&!Ee(ht))throw ht;k({path:I,size:null,type:"file",reason:Ee(ht)?"changed-during-read":"unreadable"});continue}if(Ie.isSymbolicLink()){await ti(M,I,Ie);continue}if(!Ie.isFile()){dt.nestedRepositories.has(I)||k({path:I,size:null,type:"other",reason:"changed-during-read"});continue}let Dt=dt.trackedObjectIds.get(I),ft=Dt?_.get(I):void 0;if(O&&ft?.gitObjectId!==void 0&&ft.gitObjectId===Dt&&!V.has(I)){if(m.length>=i.maxFiles){k({path:I,size:ft.size,type:"file",reason:"file-count"});continue}if(ft.size>i.maxFileBytes){k({path:I,size:ft.size,type:"file",reason:"file-size"});continue}if(R+ft.size>i.maxTotalBytes){k({path:I,size:ft.size,type:"file",reason:"total-size"});continue}m.push({...ft}),R+=ft.size,Y.add(I);continue}let Np=me&&!V.has(I)?Dt:void 0;await ne(M,I,Ie,Np),Np!==void 0&&B.add(I)}if(await ii(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await ww(r,s,a,dt,t.gitSelectionHooks?.outputChunkBytes),Y.size>0||O&&B.size>0){let I=await Gc(r,s,["ls-files","--modified","-z"],Of),M=new Set;for(let Ie of I.toString("utf8").split("\0")){let Dt=Yc(Ie);Dt!==null&&M.add(Dt)}for(let Ie of Y){if(!M.has(Ie))continue;let Dt=m.find(ft=>ft.path===Ie);z(Ie,{path:Ie,size:Dt?.size??null,type:"file",reason:"changed-during-read"})}for(let Ie of B){if(!M.has(Ie))continue;let Dt=m.find(ft=>ft.path===Ie);Dt&&delete Dt.gitObjectId}}for(let I of dt.omissions)k(I);dt.overflow&&x(dt.overflow)}m.sort((T,_)=>T.path.localeCompare(_.path,"en")),h.sort((T,_)=>T.path.localeCompare(_.path,"en"));let Yk=dt===null?{provider:"physical-tree",...y?{physicalSelection:y}:{}}:{provider:"git",...dt.evidence?{gitSelection:dt.evidence}:{}},yp=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Yk,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:E,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:N}}:{}}),yu=yp();for(;Lf(yu)>i.maxManifestBytes;){if(h.filter(_=>!Hf(_)).length>0){let _=Math.max(1,Math.ceil(h.length/4));for(let O=0;O<_;O+=1){let V=Xc(h);if(V===null)break;g(V)}}else if(m.length>0){let _=Math.max(1,Math.ceil(m.length/4));for(let O of m.splice(-_))E+=1,U(O)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");yu=yp()}return yu}async function bn(e,t,i={}){let r=(await le(e.projectRoot))?.native.snapshot??Ic;return bo(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function tl(e,t,i){let n=kw(e,t);await A(e.nativeRoot,n),await de(n,Ti(i))}async function hi(e,t){let i=kw(e,t);await A(e.nativeRoot,i);try{let n=await Lc({root:e.nativeRoot,file:i,maxBytes:Yx,label:"Native baseline snapshot manifest"});return Ti(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as i_}from"crypto";import ol from"path";import MT from"path";var at=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});function FT(e){if(e.length===0||MT.isAbsolute(e)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error("Run storage ref must stay inside the Run root")}function Ew(e){for(let t of Object.values(e))FT(t)}import{createHash as YT}from"node:crypto";import{constants as nl,promises as Qe}from"node:fs";import vt from"node:path";import{TextDecoder as XT}from"node:util";import WT from"path";var Rw=(e,t)=>{let i=e[t];return i==null?null:String(i)};function ko(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function So(e,t){let i=ko(e,t);if(WT.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function UT(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Cw(e){if(!e.run_id)return null;let t=ko(e,"run_id"),i=ko(e,"skill"),n=ko(e,"skill_version"),r=ko(e,"skill_hash"),a=So(e,"pending_ref"),o=So(e,"trajectory_ref"),s=So(e,"context_ref"),c=So(e,"artifacts_ref"),l=So(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:Rw(e,"current_step"),iteration:u,pending:Rw(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:UT(e)}}var ML=256*1024;var KT=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function GT(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Cw(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function il(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(n=>!KT.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return GT(t)}function Pw(e,t,i,n){return Ew(n),{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:i,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:n.pendingRef,trajectoryRef:n.trajectoryRef,contextRef:n.contextRef,artifactsRef:n.artifactsRef,checkpointRef:n.checkpointRef,status:"running",retries:{}}}var Ke={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Ro(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function xw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Eo(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function QT(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sn(e,t,i){let n=at[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=vt.resolve(e),a=vt.resolve(r,...n.split("/"));if(!Ro(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Aw(e){let t=await Qe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Qe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qf(e,t){let i=vt.resolve(e),n=vt.resolve(t);if(!Ro(i,n))throw new Error("Native Run path is outside its change");let r=[await Aw(i)],a=i;for(let o of vt.relative(i,n).split(vt.sep).filter(Boolean)){a=vt.join(a,o);let s;try{s=await Aw(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ro(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function rl(e){for(let t of e){let i=await Qe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!QT(t,i)||await Qe.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function ZT(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function Qn(e,t,i,n,r){let a=await qf(e,vt.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await Qe.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=xw(o),c=await Qe.realpath(t);if(!Ro(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?nl.O_RDONLY:nl.O_RDONLY|nl.O_NOFOLLOW|nl.O_NONBLOCK,u;try{u=await Qe.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Qe.lstat(t),Qe.realpath(t)]);if(await rl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Eo(s,d)||!Eo(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await ZT(u,i,n);await r?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([u.stat(),Qe.lstat(t),Qe.realpath(t)]);if(await rl(a),!v.isFile()||v.isSymbolicLink()||b!==c||!Eo(s,h)||!Eo(s,v))throw new Error(`${n} changed while reading`);let E;try{E=new XT("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`${n} is not valid UTF-8`,{cause:N})}return{text:E,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function e_(e,t,i){let n=await qf(e,vt.dirname(t));if(!n)return{exists:!1};let r;try{r=await Qe.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Qe.realpath(t);if(!Ro(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await rl(n),{exists:!0,identity:xw(r),realPath:a}}async function t_(e,t,i,n){let r=await qf(e,vt.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await Qe.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Eo(i.identity,a)||await Qe.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await rl(r)}async function al(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await e_(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await je(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await t_(e.changeDir,e.file,i,e.label)}});let n=await Qn(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Tw(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function _w(e){return`${JSON.stringify(e,null,2)}
176
- `}function kn(e){return il(e)}function Iw(e,t,i){return Pw(e,t,i,at)}async function ye(e,t){let i=Sn(e,"stateRef"),n=await Qn(e,i,Ke.runStateBytes,"Native Run state",t);return n?il(Tw(n.text,"Native Run state")):null}async function Zn(e,t,i){let n=il(t);await al({changeDir:e,file:Sn(e,"stateRef"),content:_w(n),maxBytes:Ke.runStateBytes,label:"Native Run state",hooks:i})}async function qe(e,t,i){let n=Sn(e,"trajectoryRef",t),r=await Qn(e,n,Ke.trajectoryBytes,"Native Run trajectory",i);if(!r)return[];let a=r.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ke.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ke.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function jw(e,t,i){return(await Qn(e,Sn(e,"trajectoryRef",t),Ke.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Ow(e,t,i,n,r){if(!/^[a-f0-9]{64}$/u.test(n))throw new Error("Native Run trajectory expected hash is invalid");let a=Sn(e,"trajectoryRef",t),o=await Qn(e,a,Ke.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(YT("sha256").update(o.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await al({changeDir:e,file:a,content:i,maxBytes:Ke.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:r})}async function $w(e,t,i,n){let r=Sn(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
177
- `;if(Buffer.byteLength(a,"utf8")>Ke.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ke.trajectoryEventBytes} bytes`);let o=await Qn(e,r,Ke.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ke.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ke.trajectoryEvents} events`);await al({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Ke.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function Jr(e,t,i){let n=await Qn(e,Sn(e,"checkpointRef",t),Ke.checkpointBytes,"Native Run checkpoint",i);return n?Tw(n.text,"Native Run checkpoint"):null}async function Hw(e,t,i,n){await al({changeDir:e,file:Sn(e,"checkpointRef",t),content:_w(i),maxBytes:Ke.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var n_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Bf(e){return i_("sha256").update(e).digest("hex")}function r_(e,t){if(!n_.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=ol.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return ol.join(i,"runtime","trajectory.jsonl")}function a_(e){let t=e.split(/\n/u),i=0;for(let n=0;n<t.length;n+=1){let r=t[n].endsWith("\r")?t[n].slice(0,-1):t[n];if(r.length!==0){i=n+1;try{JSON.parse(r)}catch(a){return{status:"invalid",line:n+1,message:a.message}}}}return{status:"valid",count:i}}function o_(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function s_(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=a_(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
178
- `)])}catch(d){if(!o_(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Bf(t),targetHash:Bf(l),tailHash:Bf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Dw(e,t){let i=r_(e,t);await A(e.nativeRoot,i);let n=ol.join(e.changesDir,t),r=await jw(n,at.trajectoryRef);return r===null?{status:"clean",file:i}:s_(i,Buffer.from(r))}async function zr(e,t){let i=await Dw(e,t);return"inspection"in i?i.inspection:i}async function Co(e,t){let i=await zr(e,t);if(i.status!=="clean")throw new sl(i)}async function Mw(e,t,i){return re(e,`repair trajectory tail for ${t}`,async()=>{let n=await Dw(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new sl(n)}try{await Ow(ol.join(e.changesDir,t),at.trajectoryRef,n.targetContent,n.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await zr(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return n.inspection})}import{createHash as c_}from"node:crypto";import{promises as cl}from"node:fs";import En from"node:path";var Po=/^[a-f0-9]{64}$/u,l_=16*1024,u_=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Wr(e){return u_.has(e)}function qw(e,t){let i=En.relative(e,t);return En.isAbsolute(i)||i===".."||i.startsWith(`..${En.sep}`)?null:i.replaceAll("\\","/")||"."}function d_(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Bw(e,t){if(e.length===0||d_(e)||e.includes("\\")||En.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=En.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Vf(e,t){return c_("sha256").update(`${e}
175
+ ${Buffer.byteLength(n)}:${n}`)}function Hf(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Xc(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Hf(i))return e.splice(t,1),i}return null}function gn(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function OT(e,t,i,n){if(!q(n))return{status:"budget-exhausted"};let r;try{r=await fe.open(e,"r")}catch(c){if(!q(n))return{status:"budget-exhausted"};throw c}if(!q(n))return await r.close(),{status:"budget-exhausted"};let a=Qc("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!q(n))return{status:"budget-exhausted"};let c=await r.stat();if(!q(n))return{status:"budget-exhausted"};if(!c.isFile()||!gn(i,c))return{status:"changed"};for(;;){if(!q(n))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await r.read(o,0,Math.min(o.length,l),null);if(!q(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!q(n))return{status:"budget-exhausted"};let d=await r.stat();return q(n)?!d.isFile()||!gn(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function At(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xt(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Br(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function fi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Sw(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=Z.posix.normalize(e);if(i!==e||Z.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function $T(e,t){let i=At(e,`Native snapshot entry ${t}`);xt(i,cT,`Native snapshot entry ${t}`);let n=Sw(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Zc.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let r={path:n,hash:i.hash,size:fi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!fw.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function HT(e,t){let i=At(e,`Native snapshot omission ${t}`);if(xt(i,lT,`Native snapshot omission ${t}`),!fT.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!hT.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Sw(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:fi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function DT(e){let t=At(e,"Native snapshot omission overflow");if(xt(t,uT,"Native snapshot omission overflow"),typeof t.hash!="string"||!Zc.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:Br(t.count,"Native snapshot omission overflow count")}}function qr(e,t){let i=At(e,t);if(xt(i,aT,t),typeof i.hash!="string"||!Zc.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=fi(i.recordCount,`${t} recordCount`),r=fi(i.storedRecordCount,`${t} storedRecordCount`),a=fi(i.stdoutBytes,`${t} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function lw(e){let t=At(e,"Native Git selection evidence");if(xt(t,rT,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=qr(t.stageBefore,"Native Git selection stageBefore"),n=qr(t.combined,"Native Git selection combined"),r=qr(t.stageAfter,"Native Git selection stageAfter"),a=qr(t.finalStageBefore,"Native Git selection finalStageBefore"),o=qr(t.finalCombined,"Native Git selection finalCombined"),s=qr(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!wn(i,r)||!wn(r,a)||!wn(n,o)||!wn(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:n,stageAfter:r,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function uw(e,t){let i=At(e,t);if(xt(i,sT,t),typeof i.hash!="string"||!Zc.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=fi(i.visitedNodeCount,`${t} visitedNodeCount`),r=fi(i.recordCount,`${t} recordCount`),a=fi(i.storedRecordCount,`${t} storedRecordCount`),o=fi(i.encodedBytes,`${t} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function MT(e){let t=At(e,"Native physical selection evidence");if(xt(t,oT,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=uw(t.before,"Native physical selection before"),n=uw(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!yw(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(t.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 Ti(e){let t=At(e,"Native content snapshot manifest");if(xt(t,Zx,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!dT.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let w=At(t.capture,"Native content snapshot capture");if(xt(w,iT,"Native content snapshot capture"),w.provider!=="git"&&w.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let y=w.gitSelection===void 0?void 0:lw(w.gitSelection),g=w.physicalSelection===void 0?void 0:MT(w.physicalSelection),k=null;if(w.projection!==void 0){let x=At(w.projection,"Native content snapshot projection");if(xt(x,nT,"Native content snapshot projection"),x.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");k={provider:"git",...x.selection===void 0?{}:{selection:lw(x.selection)}}}if(w.provider==="git"){if(g||k)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...y?{gitSelection:y}:{}}}else{if(y)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&k)throw new Error("Native physical-tree capture cannot combine selection and projection");i=k?{provider:"physical-tree",projection:k}:{provider:"physical-tree",...g?{physicalSelection:g}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=At(t.limits,"Native content snapshot limits");xt(n,eT,"Native content snapshot limits");let r={maxFiles:Br(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Br(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Br(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Br(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:Br(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let w=At(t.policy,"Native snapshot policy");if(xt(w,tT,"Native snapshot policy"),w.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(w.include)||!Array.isArray(w.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=bw({include:w.include,exclude:w.exclude,hash:w.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map($T),s=t.omitted.map(HT),c=fi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:DT(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(w=>w.size>r.maxFileBytes)||o.reduce((w,y)=>w+y.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(w=>w.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Df||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(w=>w.reason==="git-enumeration-limit"),f=s.filter(w=>w.reason==="git-selection-changed");for(let w of[...d,...f])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=i?.provider==="git"?i.gitSelection:i?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(w=>w.reason==="physical-enumeration-limit"),b=s.filter(w=>w.reason==="physical-selection-changed");for(let w of[...v,...b])if(w.path!=="."||w.size!==null||w.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let E=i?.physicalSelection,N=E?.status==="overflow"||E?.status==="overflow-and-changed",S=E?.status==="changed"||E?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let R={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Lf(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function Nn(e,t,i={}){let n=Ti(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=Z.resolve(e.projectRoot),a=hw(i),o=pw(i.gitSelectionLimits),s=await gw(a,r,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(Nw(s).filter(g=>wo(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>wo(e,g)),d=(g,k)=>k.some(x=>g===x||g.startsWith(`${x}/`)),f=g=>d(g,l),p=g=>d(g,u),m=[...n.entries.map(g=>g.path),...n.omitted.flatMap(g=>g.type==="directory"?[g.path,`${g.path}/`]:[g.path])].filter(g=>!c.has(g)&&!f(g)&&!p(g)),h=await bT(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!p(g.path)&&wo(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await ww(a,r,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let g of l)b.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,k)=>g.path.localeCompare(k.path,"en"));let E=n.omitted.filter(g=>f(g.path)||p(g.path)||!wo(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(k=>k.startsWith(`${g.path}/`)):!0);for(let g of b)E.some(k=>k.path===g.path&&k.reason===g.reason)||E.push(g);E.sort((g,k)=>g.path.localeCompare(k.path,"en"));let N=n.omissionOverflow?.count??0,S=n.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(N+=s.overflow.count,S=yo(S,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{N+=1,S=yo(S,"omission",g)};for(;E.length>Df;){let g=Xc(E);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let w=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:E.length+N===0,entries:v,omitted:E,omittedCount:E.length+N,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:N}}:{}}),y=w();for(;Lf(y)>n.limits.maxManifestBytes;){let g=Xc(E);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),y=w()}return Ti(y)}function kw(e,t){if(!Qx.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Z.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return Z.join(i,"runtime","baseline-manifest.json")}async function bo(e,t={}){let i={maxFiles:t.limits?.maxFiles??Uc.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Uc.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Uc.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Uc.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=bw(t.policy),r=hw({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=pw(t.gitSelectionLimits),o=yT(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=Z.resolve(e.projectRoot),c=await fe.realpath(s),l=Z.resolve(e.nativeRoot),u=await fe.realpath(l),d=Z.resolve(e.configFile),f=Z.join(s,".comet","current-change.json"),p=TT(s,t.denylist??[]),m=[],h=[],v=new Map,b=new Map,E=0,N=0,S=F("comet.native.snapshot-omission-overflow.v1"),R=0,w=!1,y=null,g=T=>{N+=1,S=yo(S,"omission",T)},k=T=>{if(E+=1,h.length<Df){h.push(T);return}if(Hf(T)){let _=Xc(h);if(_===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(_),h.push(T);return}g(T)},x=T=>{E+=T.count,N+=T.count,S=yo(S,"git-selection",{source:"git-selection",...T})},U=T=>{N+=1,S=yo(S,"manifest-entry",{reason:"manifest-size",entry:T})},D=async(T,_)=>{m.push(T),R+=T.size,v.set(T.path,_),w||(w=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(T.path))},z=(T,_)=>{let O=m.findIndex(me=>me.path===T);if(O<0)return;let[V]=m.splice(O,1);R-=V.size,v.delete(T),k(_)},ne=async(T,_,O,V)=>{if(!O.isFile()||O.isSymbolicLink()||!q(r))return;let me;try{me=await fe.realpath(T)}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;k({path:_,size:O.size,type:"file",reason:Ee(M)?"changed-during-read":"unreadable"});return}if(!q(r)||!$(c,me)||yn(u,me))return;if(m.length>=i.maxFiles){k({path:_,size:O.size,type:"file",reason:"file-count"});return}if(O.size>i.maxFileBytes){k({path:_,size:O.size,type:"file",reason:"file-size"});return}if(R+O.size>i.maxTotalBytes){k({path:_,size:O.size,type:"file",reason:"total-size"});return}let Y,B,I;try{if(Y=await OT(me,O.size,O,r),Y.status==="budget-exhausted"||!q(r))return;if(Y.status==="changed"){k({path:_,size:null,type:"file",reason:"changed-during-read"});return}if(!q(r)||(I=await fe.realpath(T),!q(r)))return;B=await fe.lstat(T)}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;k({path:_,size:O.size,type:"file",reason:Ee(M)?"changed-during-read":"unreadable"});return}if(q(r)){if(Y.bytes!==O.size||I!==me||!gn(O,Y.finalStat)||!gn(Y.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==O.size||B.mtimeMs!==O.mtimeMs||B.ctimeMs!==O.ctimeMs){k({path:_,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}q(r)&&await D({path:_,hash:Y.hash,size:B.size,type:"file",...V===void 0?{}:{gitObjectId:V}},{kind:"file",target:T,realTarget:me,stat:B})}},ti=async(T,_,O)=>{if(!q(r))return;let V,me,Y;try{if(V=await fe.readlink(T,{encoding:"buffer"}),!q(r)||(Y=await fe.lstat(T),!q(r)))return;me=await fe.readlink(T,{encoding:"buffer"})}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;k({path:_,size:null,type:"other",reason:Ee(M)?"changed-during-read":"unreadable"});return}if(!q(r))return;if(!Y.isSymbolicLink()||!gn(O,Y)||Y.mtimeMs!==O.mtimeMs||Y.ctimeMs!==O.ctimeMs||!V.equals(me)){k({path:_,size:null,type:"other",reason:"changed-during-read"});return}let B=V.byteLength;if(m.length>=i.maxFiles){k({path:_,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){k({path:_,size:B,type:"other",reason:"file-size"});return}if(R+B>i.maxTotalBytes){k({path:_,size:B,type:"other",reason:"total-size"});return}let I=Qc("sha256").update("symlink\0").update(V).digest("hex");q(r)&&await D({path:_,hash:I,size:B,type:"file"},{kind:"symlink",target:T,rawTarget:V,stat:Y})},ii=async()=>{for(let[T,_]of[...v]){if(!q(r))return;if(_.kind==="file"){let B,I;try{if(B=await fe.realpath(_.target),!q(r))return;I=await fe.lstat(_.target)}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;z(T,{path:T,size:null,type:"file",reason:Re(M)?"unreadable":"changed-during-read"});continue}if(!q(r))return;(B!==_.realTarget||!I.isFile()||I.isSymbolicLink()||!gn(_.stat,I)||I.size!==_.stat.size||I.mtimeMs!==_.stat.mtimeMs||I.ctimeMs!==_.stat.ctimeMs)&&z(T,{path:T,size:I.isFile()?I.size:null,type:I.isFile()?"file":"other",reason:"changed-during-read"});continue}if(_.kind==="symlink"){let B,I;try{if(B=await fe.lstat(_.target),!q(r))return;I=await fe.readlink(_.target,{encoding:"buffer"})}catch(M){if(!q(r))return;if(!Re(M)&&!Ee(M))throw M;z(T,{path:T,size:null,type:"other",reason:Re(M)?"unreadable":"changed-during-read"});continue}if(!q(r))return;(!B.isSymbolicLink()||!gn(_.stat,B)||B.mtimeMs!==_.stat.mtimeMs||B.ctimeMs!==_.stat.ctimeMs||!_.rawTarget.equals(I))&&z(T,{path:T,size:null,type:"other",reason:"changed-during-read"});continue}let O,V;try{if(O=await fe.realpath(_.target),!q(r))return;V=await fe.lstat(_.target)}catch{if(!q(r))return;z(T,{path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!q(r))return;if(!(O===_.realTarget&&V.isDirectory()&&!V.isSymbolicLink()&&gn(_.stat,V)&&$(c,O)&&!yn(u,O))){z(T,{path:T,size:null,type:"directory",reason:"gitlink-changed"});continue}let Y;try{if(!q(r))return;Y=await ow(r,O)}catch(B){if(No(B))throw B;z(T,{path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!q(r))return;Y.dirty?z(T,{path:T,size:null,type:"directory",reason:"gitlink-dirty"}):Y.hash!==_.hash&&z(T,{path:T,size:null,type:"directory",reason:"gitlink-changed"})}for(let[T,_]of b){if(!q(r))return;try{let O=await fe.lstat(_);if(!q(r))return;k({path:T,size:O.isFile()?O.size:null,type:O.isFile()?"file":O.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(O){if(!q(r))return;if(Ee(O))continue;if(!Re(O))throw O;k({path:T,size:null,type:"file",reason:"unreadable"})}}},dt=await gw(r,s,a,t.gitSelectionHooks);if(dt===null){let T=await rw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let V of T.records){if(V.type!=="file"&&V.type!=="symlink"||v.has(V.path))continue;if(Bt(r)<1)break;if(!cw(n,V.path,r))continue;if(Bt(r)<1)break;let me=Z.resolve(s,...V.path.split("/")),Y;try{Y=await fe.lstat(me)}catch(B){if(!q(r))break;if(!Re(B)&&!Ee(B))throw B;k({path:V.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(Bt(r)<1)break;if(V.type==="symlink"&&Y.isSymbolicLink()){if(await ti(me,V.path,Y),Bt(r)<1)break;continue}if(V.type!=="file"||!Y.isFile()||Y.isSymbolicLink()){k({path:V.path,size:Y.isFile()?Y.size:null,type:Y.isDirectory()?"directory":Y.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ne(me,V.path,Y),Bt(r)<1)break}Bt(r)>=1&&await ii();let _=await rw({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),O=AT(T.evidence,_.evidence);y=O.evidence;for(let V of[...T.omissions,..._.omissions,...O.omissions])h.some(me=>me.path===V.path&&me.reason===V.reason)||k(V)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let T=t.incrementalBaseline,_=new Map,O=!1;if(T){let I=Ti(T);for(let M of I.entries)M.gitObjectId!==void 0&&_.set(M.path,M);O=_.size>0}let V=new Set,me=!0;try{let I=await Gc(r,s,["ls-files","--modified","-z"],Of);for(let M of I.toString("utf8").split("\0")){let Ie=Yc(M);Ie!==null&&V.add(Ie)}}catch{O=!1,me=!1,_.clear()}let Y=new Set,B=new Set;for(let I of Nw(dt)){if(v.has(I)||!wo(e,I))continue;if(Bt(r)<1)break;if(!cw(n,I,r))continue;if(Bt(r)<1)break;let M=Z.resolve(s,...I.split("/"));if(M===d||M===f||p.some(ht=>yn(ht,M)))continue;if(dt.gitlinks.has(I)){if(m.length>=i.maxFiles){k({path:I,size:0,type:"file",reason:"file-count"});continue}let ht,hs;try{[ht,hs]=await Promise.all([fe.realpath(M),fe.lstat(M)])}catch{k({path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(hs.isSymbolicLink()||!hs.isDirectory()||!$(c,ht)||yn(u,ht)){k({path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let br=await ow(r,ht);if(br.dirty){k({path:I,size:null,type:"directory",reason:"gitlink-dirty"});continue}await D({path:I,hash:br.hash,size:0,type:"file"},{kind:"gitlink",target:M,realTarget:ht,stat:hs,hash:br.hash})}catch(br){if(No(br))throw br;k({path:I,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let Ie;try{Ie=await fe.lstat(M)}catch(ht){if(Ee(ht)&&dt.tracked.has(I)){b.set(I,M);continue}if(!Re(ht)&&!Ee(ht))throw ht;k({path:I,size:null,type:"file",reason:Ee(ht)?"changed-during-read":"unreadable"});continue}if(Ie.isSymbolicLink()){await ti(M,I,Ie);continue}if(!Ie.isFile()){dt.nestedRepositories.has(I)||k({path:I,size:null,type:"other",reason:"changed-during-read"});continue}let Dt=dt.trackedObjectIds.get(I),ft=Dt?_.get(I):void 0;if(O&&ft?.gitObjectId!==void 0&&ft.gitObjectId===Dt&&!V.has(I)){if(m.length>=i.maxFiles){k({path:I,size:ft.size,type:"file",reason:"file-count"});continue}if(ft.size>i.maxFileBytes){k({path:I,size:ft.size,type:"file",reason:"file-size"});continue}if(R+ft.size>i.maxTotalBytes){k({path:I,size:ft.size,type:"file",reason:"total-size"});continue}m.push({...ft}),R+=ft.size,Y.add(I);continue}let Np=me&&!V.has(I)?Dt:void 0;await ne(M,I,Ie,Np),Np!==void 0&&B.add(I)}if(await ii(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await ww(r,s,a,dt,t.gitSelectionHooks?.outputChunkBytes),Y.size>0||O&&B.size>0){let I=await Gc(r,s,["ls-files","--modified","-z"],Of),M=new Set;for(let Ie of I.toString("utf8").split("\0")){let Dt=Yc(Ie);Dt!==null&&M.add(Dt)}for(let Ie of Y){if(!M.has(Ie))continue;let Dt=m.find(ft=>ft.path===Ie);z(Ie,{path:Ie,size:Dt?.size??null,type:"file",reason:"changed-during-read"})}for(let Ie of B){if(!M.has(Ie))continue;let Dt=m.find(ft=>ft.path===Ie);Dt&&delete Dt.gitObjectId}}for(let I of dt.omissions)k(I);dt.overflow&&x(dt.overflow)}m.sort((T,_)=>T.path.localeCompare(_.path,"en")),h.sort((T,_)=>T.path.localeCompare(_.path,"en"));let Yk=dt===null?{provider:"physical-tree",...y?{physicalSelection:y}:{}}:{provider:"git",...dt.evidence?{gitSelection:dt.evidence}:{}},yp=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:Yk,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:E,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:N}}:{}}),yu=yp();for(;Lf(yu)>i.maxManifestBytes;){if(h.filter(_=>!Hf(_)).length>0){let _=Math.max(1,Math.ceil(h.length/4));for(let O=0;O<_;O+=1){let V=Xc(h);if(V===null)break;g(V)}}else if(m.length>0){let _=Math.max(1,Math.ceil(m.length/4));for(let O of m.splice(-_))E+=1,U(O)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");yu=yp()}return yu}async function bn(e,t,i={}){let r=(await le(e.projectRoot))?.native.snapshot??Ic;return bo(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:r.max_files,maxFileBytes:r.max_total_bytes,maxTotalBytes:r.max_total_bytes,maxDurationMs:r.max_duration_ms},deadlineMs:r.max_duration_ms})}async function tl(e,t,i){let n=kw(e,t);await A(e.nativeRoot,n),await de(n,Ti(i))}async function hi(e,t){let i=kw(e,t);await A(e.nativeRoot,i);try{let n=await Lc({root:e.nativeRoot,file:i,maxBytes:Xx,label:"Native baseline snapshot manifest"});return Ti(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as n_}from"crypto";import ol from"path";import FT from"path";var at=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});function LT(e){if(e.length===0||FT.isAbsolute(e)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error("Run storage ref must stay inside the Run root")}function Ew(e){for(let t of Object.values(e))LT(t)}import{createHash as XT}from"node:crypto";import{constants as nl,promises as Qe}from"node:fs";import vt from"node:path";import{TextDecoder as QT}from"node:util";import UT from"path";var Rw=(e,t)=>{let i=e[t];return i==null?null:String(i)};function ko(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function So(e,t){let i=ko(e,t);if(UT.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function KT(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(i))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function Cw(e){if(!e.run_id)return null;let t=ko(e,"run_id"),i=ko(e,"skill"),n=ko(e,"skill_version"),r=ko(e,"skill_hash"),a=So(e,"pending_ref"),o=So(e,"trajectory_ref"),s=So(e,"context_ref"),c=So(e,"artifacts_ref"),l=So(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:i,skillVersion:n,skillHash:r,orchestration:e.orchestration,currentStep:Rw(e,"current_step"),iteration:u,pending:Rw(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:KT(e)}}var FL=256*1024;var GT=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function YT(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},i=Cw(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function il(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(n=>!GT.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return YT(t)}function Pw(e,t,i,n){return Ew(n),{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:i,orchestration:e.definition.orchestration.mode,currentStep:e.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:n.pendingRef,trajectoryRef:n.trajectoryRef,contextRef:n.contextRef,artifactsRef:n.artifactsRef,checkpointRef:n.checkpointRef,status:"running",retries:{}}}var Ke={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Ro(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function xw(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Eo(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function ZT(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sn(e,t,i){let n=at[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=vt.resolve(e),a=vt.resolve(r,...n.split("/"));if(!Ro(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Aw(e){let t=await Qe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Qe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qf(e,t){let i=vt.resolve(e),n=vt.resolve(t);if(!Ro(i,n))throw new Error("Native Run path is outside its change");let r=[await Aw(i)],a=i;for(let o of vt.relative(i,n).split(vt.sep).filter(Boolean)){a=vt.join(a,o);let s;try{s=await Aw(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ro(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function rl(e){for(let t of e){let i=await Qe.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!ZT(t,i)||await Qe.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function e_(e,t,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-r,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>t)throw new Error(`${i} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function Qn(e,t,i,n,r){let a=await qf(e,vt.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await Qe.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${n} must be a regular file`);if(o.size>i)throw new Error(`${n} exceeds ${i} bytes`);let s=xw(o),c=await Qe.realpath(t);if(!Ro(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?nl.O_RDONLY:nl.O_RDONLY|nl.O_NOFOLLOW|nl.O_NONBLOCK,u;try{u=await Qe.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Qe.lstat(t),Qe.realpath(t)]);if(await rl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Eo(s,d)||!Eo(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await e_(u,i,n);await r?.beforeFinalCheck?.();let[h,v,b]=await Promise.all([u.stat(),Qe.lstat(t),Qe.realpath(t)]);if(await rl(a),!v.isFile()||v.isSymbolicLink()||b!==c||!Eo(s,h)||!Eo(s,v))throw new Error(`${n} changed while reading`);let E;try{E=new QT("utf-8",{fatal:!0}).decode(m)}catch(N){throw new Error(`${n} is not valid UTF-8`,{cause:N})}return{text:E,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function t_(e,t,i){let n=await qf(e,vt.dirname(t));if(!n)return{exists:!1};let r;try{r=await Qe.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!r.isFile()||r.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await Qe.realpath(t);if(!Ro(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await rl(n),{exists:!0,identity:xw(r),realPath:a}}async function i_(e,t,i,n){let r=await qf(e,vt.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await Qe.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${n} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Eo(i.identity,a)||await Qe.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await rl(r)}async function al(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await t_(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await je(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await i_(e.changeDir,e.file,i,e.label)}});let n=await Qn(e.changeDir,e.file,e.maxBytes,e.label);if(!n||n.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function Tw(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function _w(e){return`${JSON.stringify(e,null,2)}
176
+ `}function kn(e){return il(e)}function Iw(e,t,i){return Pw(e,t,i,at)}async function ye(e,t){let i=Sn(e,"stateRef"),n=await Qn(e,i,Ke.runStateBytes,"Native Run state",t);return n?il(Tw(n.text,"Native Run state")):null}async function Zn(e,t,i){let n=il(t);await al({changeDir:e,file:Sn(e,"stateRef"),content:_w(n),maxBytes:Ke.runStateBytes,label:"Native Run state",hooks:i})}async function qe(e,t,i){let n=Sn(e,"trajectoryRef",t),r=await Qn(e,n,Ke.trajectoryBytes,"Native Run trajectory",i);if(!r)return[];let a=r.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ke.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ke.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function jw(e,t,i){return(await Qn(e,Sn(e,"trajectoryRef",t),Ke.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Ow(e,t,i,n,r){if(!/^[a-f0-9]{64}$/u.test(n))throw new Error("Native Run trajectory expected hash is invalid");let a=Sn(e,"trajectoryRef",t),o=await Qn(e,a,Ke.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(XT("sha256").update(o.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await al({changeDir:e,file:a,content:i,maxBytes:Ke.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:r})}async function $w(e,t,i,n){let r=Sn(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
177
+ `;if(Buffer.byteLength(a,"utf8")>Ke.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ke.trajectoryEventBytes} bytes`);let o=await Qn(e,r,Ke.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ke.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ke.trajectoryEvents} events`);await al({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Ke.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function Jr(e,t,i){let n=await Qn(e,Sn(e,"checkpointRef",t),Ke.checkpointBytes,"Native Run checkpoint",i);return n?Tw(n.text,"Native Run checkpoint"):null}async function Hw(e,t,i,n){await al({changeDir:e,file:Sn(e,"checkpointRef",t),content:_w(i),maxBytes:Ke.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var r_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sl=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Bf(e){return n_("sha256").update(e).digest("hex")}function a_(e,t){if(!r_.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=ol.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return ol.join(i,"runtime","trajectory.jsonl")}function o_(e){let t=e.split(/\n/u),i=0;for(let n=0;n<t.length;n+=1){let r=t[n].endsWith("\r")?t[n].slice(0,-1):t[n];if(r.length!==0){i=n+1;try{JSON.parse(r)}catch(a){return{status:"invalid",line:n+1,message:a.message}}}}return{status:"valid",count:i}}function s_(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function c_(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=o_(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:e,line:r.line,message:r.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=r.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
178
+ `)])}catch(d){if(!s_(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Bf(t),targetHash:Bf(l),tailHash:Bf(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function Dw(e,t){let i=a_(e,t);await A(e.nativeRoot,i);let n=ol.join(e.changesDir,t),r=await jw(n,at.trajectoryRef);return r===null?{status:"clean",file:i}:c_(i,Buffer.from(r))}async function zr(e,t){let i=await Dw(e,t);return"inspection"in i?i.inspection:i}async function Co(e,t){let i=await zr(e,t);if(i.status!=="clean")throw new sl(i)}async function Mw(e,t,i){return re(e,`repair trajectory tail for ${t}`,async()=>{let n=await Dw(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new sl(n)}try{await Ow(ol.join(e.changesDir,t),at.trajectoryRef,n.targetContent,n.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await zr(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return n.inspection})}import{createHash as l_}from"node:crypto";import{promises as cl}from"node:fs";import En from"node:path";var Po=/^[a-f0-9]{64}$/u,u_=16*1024,d_=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Wr(e){return d_.has(e)}function qw(e,t){let i=En.relative(e,t);return En.isAbsolute(i)||i===".."||i.startsWith(`..${En.sep}`)?null:i.replaceAll("\\","/")||"."}function f_(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Bw(e,t){if(e.length===0||f_(e)||e.includes("\\")||En.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=En.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Vf(e,t){return l_("sha256").update(`${e}
179
179
  ${t}`).digest("hex")}async function Fw(e,t){let i=await cl.realpath(t),n=await cl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?En.normalize(i).toLowerCase():i;return Vf(e,`${r}
180
180
  ${n.dev}
181
181
  ${n.ino}
182
- ${n.birthtimeMs}`)}async function Lw(e,t){let i=await cl.realpath(t),n=await cl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?En.normalize(i).toLowerCase():i;return Vf(e,r)}function f_(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ll(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Po.test(String(t.projectRootId))||!Po.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");f_(t.capturedAt),Bw(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!Po.test(String(t.projectRootPathId))||a&&!Po.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Po.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid")}function Ur(e,t){return En.join(e.changesDir,t,"runtime","workspace.json")}function h_(e,t){let i=qw(e.nativeRoot,Ur(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Bw(i,"Native workspace file ref")}async function Vw(e,t){try{let i=await ge({root:e.nativeRoot,ref:h_(e,t),maxBytes:l_});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Jf(e,t){let i=await Vw(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(ll(i),i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function Jw(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=qw(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([Fw("comet.native.workspace-project-root.v2",e.paths.projectRoot),Fw("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Lw("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Lw("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),s={schema:"comet.native.workspace.v2",capturedAt:(e.now??new Date).toISOString(),capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:Vf("comet.native.workspace-session.v2",`${i}
182
+ ${n.birthtimeMs}`)}async function Lw(e,t){let i=await cl.realpath(t),n=await cl.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?En.normalize(i).toLowerCase():i;return Vf(e,r)}function h_(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ll(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash"]),n=Object.keys(t).filter(o=>!i.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Po.test(String(t.projectRootId))||!Po.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");h_(t.capturedAt),Bw(t.nativeRootRef,"Native workspace root ref");let r=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(r!==a)throw new Error("Native workspace path identities must be provided together");if(r&&!Po.test(String(t.projectRootPathId))||a&&!Po.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Po.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid")}function Ur(e,t){return En.join(e.changesDir,t,"runtime","workspace.json")}function p_(e,t){let i=qw(e.nativeRoot,Ur(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return Bw(i,"Native workspace file ref")}async function Vw(e,t){try{let i=await ge({root:e.nativeRoot,ref:p_(e,t),maxBytes:u_});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Jf(e,t){let i=await Vw(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(ll(i),i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function Jw(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=qw(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let[i,n,r,a]=await Promise.all([Fw("comet.native.workspace-project-root.v2",e.paths.projectRoot),Fw("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Lw("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Lw("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),s={schema:"comet.native.workspace.v2",capturedAt:(e.now??new Date).toISOString(),capturedRevision:e.revision,nativeRootRef:t,projectRootId:i,nativeRootId:n,projectRootPathId:r,nativeRootPathId:a,...e.sessionId?{sessionHash:Vf("comet.native.workspace-session.v2",`${i}
183
183
  ${n}
184
- ${e.sessionId}`)}:{}};return ll(s),s}async function Ao(e){let t=await Jw(e),i=Ur(e.paths,e.name);return await A(e.paths.nativeRoot,i),await de(i,t,{containedRoot:e.paths.nativeRoot}),t}async function ul(e,t){let i=await Vw(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ll(i),i)}async function zw(e){return await Jf(e.paths,e.name)?Ao(e):null}async function Ww(e){ll(e.identity);let t=await Jw({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),process.platform==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}var Ce="comet.native.v3",Oe="comet.native.v2",Tt="comet.native.v1",_i="comet.native.transition.v3",Ii="comet.native.transition.v2",er="comet.native.transition.v1";var Uw=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],p_=new Set(Uw),Kw=new Set([...Uw,"minimum_runtime_version","revision"]),m_=new Set([...Kw,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),v_=new Set(["capability","operation","source","base_hash"]),g_=new Set(["shape","build","verify","archive"]),w_=new Set(["implicit","confirmed"]),y_=new Set(["pending","pass","fail"]),$e="comet-state.yaml",Wf=/^[a-f0-9]{64}$/u,Gw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,N_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,xo=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"},Oi=class extends Error{constructor(i,n){super(i!==Ce||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"},Cn=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"},pi=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"},b_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
185
- `);function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Yw(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Vt(e){if(!Gw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function S_(e){if(!Gw.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Xw(e,t){if(e.length===0||gt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function k_(e,t){let i=Io(e,`spec_changes[${t}]`);if(Yw(i,v_,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(S_(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"&&Xw(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"||!Wf.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"||!Wf.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 E_(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Uf(e,t){if(Yw(e,t,$e),typeof e.name!="string")throw new Error("Native change name is required");if(Vt(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!g_.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!w_.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(k_),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 e.verification_result!="string"||!y_.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Xw(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!E_(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function jo(e){let t=Io(e,$e);if(t.schema!==Tt)throw new Error(`Expected ${Tt}`);return{schema:Tt,...Uf(t,p_)}}function To(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function zf(e,t,i){if(e===null)return null;let n=typeof e=="string"?N_.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function R_(e){if(e==null)return null;if(typeof e!="string"||!Wf.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function C_(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Pn(e){let t=Io(e,$e);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);if(To(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Oe} minimum_runtime_version must be 2`);return{schema:Oe,minimum_runtime_version:2,revision:To(t.revision,"Native v2 revision"),...Uf(t,Kw)}}function _t(e){let t=Io(e,$e);if(t.schema!==Ce){if(t.schema===Tt||t.schema===Oe){let o=t.schema===Tt?jo(t):Pn(t);throw new xo(o.name,o.schema)}throw new Oi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=To(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Oi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=To(t.revision,"Native revision"),r=Uf(t,m_),a=R_(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ce,minimum_runtime_version:3,revision:n,verification_protocol:C_(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:zf(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:zf(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:zf(t.partial_allowance,"Native partial_allowance","allowances")}}function P_(e){let t=Io(e,$e);if(t.schema===Tt){let r=jo(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Ce}`}}if(t.schema===Oe){let r=Pn(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Ce}`}}if(t.schema!==Ce){let r=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Oi(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=To(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Oi(t.schema,i).message};let n=_t(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Rn(e){let t=_t(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function dl(e){let t=Pn(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function C(e,t){Vt(t);let i=gt.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function tr(e,t){let i=gt.join(C(e,t),"runtime","schema-migration.json");await A(e.nativeRoot,i);try{return await ji.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Kr(e,t){let i=gt.join(C(e,t),"runtime","checkpoint-journal.json");await A(e.nativeRoot,i);try{return await ji.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qw(e){return re(e.paths,`create change ${e.name}`,()=>A_(e))}async function A_(e){Vt(e.name);let t=e.verificationProtocol??"legacy-v1",i=C(e.paths,e.name);await A(e.paths.nativeRoot,i);let n=!1;try{try{await ji.mkdir(i,{recursive:!1}),n=!0}catch(c){if(c.code==="ENOENT"){await ji.mkdir(e.paths.changesDir,{recursive:!0});try{await ji.mkdir(i,{recursive:!1}),n=!0}catch(l){throw l.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:l}):l}}else throw c.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:c}):c}let r={schema:Ce,minimum_runtime_version:3,revision:1,verification_protocol:t,name:e.name,language:e.language,phase:"shape",brief:"brief.md",approval:null,approved_contract_hash:null,spec_changes:[],verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1,created_at:(e.now??new Date).toISOString().slice(0,10),run_id:null};await Promise.all([ji.mkdir(gt.join(i,"specs"),{recursive:!0}),ji.mkdir(gt.join(i,"runtime","checkpoints"),{recursive:!0}),je(gt.join(i,"brief.md"),b_)]);let o=(await le(e.paths.projectRoot))?.native.snapshot??Ic,s=await bo(e.paths,{now:e.now,origin:"change-created",policy:o,limits:{maxFiles:o.max_files,maxFileBytes:o.max_total_bytes,maxTotalBytes:o.max_total_bytes,maxDurationMs:o.max_duration_ms},deadlineMs:o.max_duration_ms});if(!s.complete){let c=el(s),l=s.omitted.reduce((d,f)=>(d[f.reason]=(d[f.reason]??0)+1,d),{}),u=s.omissionOverflow?.count??0;throw u>0&&(l.overflow=u),new pi(r.name,s.omittedCount,l,c.samplePaths,c.sampleTruncated,s.limits,s.policy?.hash??null)}return await tl(e.paths,r.name,s),await __(e.paths,r),await Ao({paths:e.paths,name:r.name,revision:r.revision,now:e.now}),r}catch(r){throw n&&await ji.rm(i,{recursive:!0,force:!0}),r}}var x_=256*1024;async function Kf(e,t=gt.dirname(e)){let i=gt.relative(t,e).split(gt.sep).join("/"),n=await ge({root:t,ref:i,maxBytes:x_}),r=(0,_o.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${r.errors[0].message}`);return r.toJS()}async function ot(e,t){let i=gt.join(C(e,t),$e);await A(e.nativeRoot,i);let n=P_(await Kf(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await tr(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await T_(e,n.state),n)}async function T_(e,t){if(await hi(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function W(e,t){let i=await ot(e,t);if(i.status==="migration-required")throw new xo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Oi(i.schema,i.minimumRuntimeVersion);return i.state}async function __(e,t){let i=gt.join(C(e,t.name),$e);await A(e.nativeRoot,i);try{throw await ji.access(i),new Error(`Native change state already exists: ${t.name}`)}catch(n){if(n.code!=="ENOENT")throw n}if(t.revision!==1)throw new Error("New Native change must start at revision 1");await je(i,(0,_o.stringify)(Rn(t)))}async function Zw(e,t,i){let n={...t,schema:Ce,minimum_runtime_version:3,revision:i+1},r=await tw({expectedRevision:i,next:n,read:async()=>{let a=_t(await Kf(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>je(e,(0,_o.stringify)(Rn(a))),equals:(a,o)=>JSON.stringify(Rn(a))===JSON.stringify(Rn(o)),conflict:a=>new Cn(t.name,i,a)});return Object.assign(t,r),r}async function Gr(e,t,i,n){if(await $r(e.projectRoot),await tr(e,t.name))throw new xo(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await Kr(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await W(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Co(e,t.name);let a=gt.join(C(e,t.name),$e);return await A(e.nativeRoot,a),Zw(a,t,i)}async function ey(e,t){return Zw(e,t,t.revision)}async function ty(e){return _t(await Kf(e))}var ny=["Outcome","Scope","Non-goals","Acceptance examples"],I_=[...ny,"Constraints and invariants","Decisions","Open questions","Verification expectations"],j_=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],ry={maxFileBytes:eo};function ay(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
186
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function oy(e,t){let i=iy.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Gf.realpath(e),r=await Gf.realpath(i);if(!$(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Gf.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Oo(e){return{valid:e.length===0,findings:e}}async function ir(e,t){let i=[],n;try{n=(await ge({root:e,ref:t,maxBytes:ry.maxFileBytes})).text}catch(o){return Oo([{code:"brief-missing",message:o.message,path:t}])}let r=ay(n);for(let o of I_)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of ny)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Oo(i)}async function Yr(e,t){let i=[],n;try{n=(await ge({root:e,ref:t,maxBytes:ry.maxFileBytes})).text}catch(a){return Oo([{code:"verification-missing",message:a.message,path:t}])}let r=ay(n);for(let a of j_)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Oo(i)}function Jt(e,t){return iy.join(e.specsDir,t,"spec.md")}async function Xr(e,t){let i=[],n=C(e,t.name);for(let r of t.spec_changes){let a=Jt(e,r.capability),o=null;try{await A(e.nativeRoot,a),o=await rt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(r.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${r.capability}`,path:a}),r.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${r.capability}`,path:a}),r.operation!=="create"&&o!==null&&o!==r.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${r.capability}: expected ${r.base_hash}, actual ${o}`,path:a}),r.source)try{await oy(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Oo(i)}async function sy(e,t){return oy(e,t)}import{promises as c$}from"node:fs";import _b from"node:path";import cy from"node:path";import{createHash as O_}from"crypto";function zt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function $_(e,t){t.has(e)&&zt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||zt("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&zt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&zt("symbol properties are not supported"),`[${e.map(n=>Yf(n,t)).join(",")}]`}finally{t.delete(e)}}function H_(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&zt("only plain objects are supported"),t.has(e)&&zt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&zt("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&zt("accessor properties are not supported"),`${JSON.stringify(o)}:${Yf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Yf(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||zt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?$_(e,t):H_(e,t);case"bigint":case"function":case"symbol":case"undefined":return zt(`${typeof e} values are not supported`)}return zt("unsupported value type")}function $o(e){return Yf(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return O_("sha256").update(`${e}
187
- ${$o(t)}`).digest("hex")}var D_="comet.native.archive-preflight.v1",M_="comet.native.archive-preflight.v1",F_="comet.native.archive-operation.v1",L_=/^[a-f0-9]{64}$/u,ly=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,q_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function fl(e,t){return e<t?-1:e>t?1:0}function B_(e,t){if(typeof e!="string"||!L_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $i(e,t){return e===null?null:B_(e,t)}function V_(e,t){let i=cy.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||cy.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function J_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function z_(e,t){if(!ly.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=$i(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=$i(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=$i(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function W_(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:$i(e.contractHash,"Native archive contract hash"),acceptanceHash:$i(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:$i(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:$i(e.reportHash,"Native archive report hash"),envelopeHash:$i(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:$i(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function U_(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!q_.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(fl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function K_(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(fl)}function uy(e){if(!ly.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(z_).sort((c,l)=>fl(c.capability,l.capability));if(new Set(t.map(c=>c.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(c=>({...c,operationHash:H(F_,c)})),n=W_(e.evidence),r=[...new Set([...U_(e.findingCodes??[]),...K_({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(fl),a=J_(e.revision),o=V_(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let s={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:o,targetExists:e.targetExists,operations:i,evidence:n,findingCodes:r};return{schema:D_,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,targetRef:o,ready:r.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,findingCodes:r,preflightHash:H(M_,s)}}import{createHash as G_}from"node:crypto";import dy from"node:path";var Y_="comet.native.conflict-radar.v1",st=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}),X_="comet.native.conflict-radar.v1",Q_="comet.native.conflict-radar-signals.v1",Z_=/^[a-f0-9]{64}$/u,py=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),tI=new Set(["capability","operation","baseHash"]),iI=new Set(["path","kind"]);function Qr(e,t){return e<t?-1:e>t?1:0}function Xf(e){return Buffer.byteLength(e,"utf8")}function Qf(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let n=e,r=Object.keys(n).filter(a=>!t.has(a));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);return n}function Zf(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Xf(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function nI(e,t){let i=Zf(e,t,st.maxArtifactPathBytes),n=dy.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||dy.posix.isAbsolute(n)||i.split("/").includes("..")||n!==i||n==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function my(e,t){if(typeof e!="string"||!Z_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rI(e,t){let i=Qf(e,tI,t),n=Zf(i.capability,`${t} capability`,st.maxCapabilityBytes);if(!py.test(n))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let r=i.baseHash===null?null:my(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&r!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&r===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:n,operation:i.operation,baseHash:r}}function aI(e,t){let i=Qf(e,iI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:nI(i.path,`${t} path`),kind:i.kind}}function oI(e,t){let i=Qf(e,eI,`Conflict radar change ${t}`),n=Zf(i.name,`Conflict radar change ${t} name`,st.maxNameBytes);if(!py.test(n))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${n} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${n} specs must be an array`);if(i.specs.length>st.maxSpecsPerChange)throw new Error(`Conflict radar change ${n} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${n} declared artifacts must be an array`);if(i.declaredArtifacts.length>st.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>rI(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Qr(c.capability,l.capability));if(new Set(r.map(c=>c.capability)).size!==r.length)throw new Error(`Conflict radar change ${n} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>aI(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Qr(c.path,l.path)||Qr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${n} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:my(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function sI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>st.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(oI).sort((r,a)=>Qr(r.name,a.name));if(new Set(t.map(r=>r.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((r,a)=>r+a.specs.length,0)>st.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>st.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function cI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function lI(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!n&&!r?null:{kind:"artifact",certainty:r?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function uI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function dI(e,t){let i=[],n=G_("sha256").update(`${Q_}
188
- [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update($o(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<st.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(cI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=lI(l,u);d&&o(d)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:uI(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function fy(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function fI(e,t){return fy(e.classification)-fy(t.classification)||Qr(e.left,t.left)||Qr(e.right,t.right)}function hy(e,t,i,n){let r={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:Y_,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:r,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:n}}function eh(e){let t=sI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(dI(t[s],t[c]));i.sort(fI);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=H(X_,{changes:t,relationships:n}),a=i.slice(0,st.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=hy(t,i,a,r);for(;a.length>0&&Xf(JSON.stringify(o))>st.maxSerializedBytes;)a=a.slice(0,-1),o=hy(t,i,a,r);if(Xf(JSON.stringify(o))>st.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as nN}from"node:crypto";import{promises as Kt}from"node:fs";import vi from"node:path";import{createHash as Sy}from"node:crypto";import vy from"path";var th="comet.native.implementation-scope.v2",ky="comet.native.content-snapshot-projection.v1",Ho="comet.native.content-snapshot-projection.v1",Ey="comet.native.implementation-scope.v2",hI="comet.native.unresolved-scope-id.v1",pI="comet.native.scope-detail-overflow.v1",mI="comet.native.snapshot-projection-overflow.v2",ah=/^[a-f0-9]{64}$/u,mi=1024*1024,vI=128,gI=128;function Ge(e,t){return e<t?-1:e>t?1:0}function ih(e){if(!ah.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function wI(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function xn(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=vy.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||vy.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Ry(e,t){return e==="."?e:xn(e,t)}function Zr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function yI(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:xn(e.path,`${t} path`),hash:e.hash,size:Zr(e.size,`${t} size`),type:"file"}}function NI(e,t){return{path:Ry(e.path,`${t} path`),size:e.size===null?null:Zr(e.size,`${t} size`),type:e.type,reason:e.reason}}function bI(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function SI(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Do(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
184
+ ${e.sessionId}`)}:{}};return ll(s),s}async function Ao(e){let t=await Jw(e),i=Ur(e.paths,e.name);return await A(e.paths.nativeRoot,i),await de(i,t,{containedRoot:e.paths.nativeRoot}),t}async function ul(e,t){let i=await Vw(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(ll(i),i)}async function zw(e){return await Jf(e.paths,e.name)?Ao(e):null}async function Ww(e){ll(e.identity);let t=await Jw({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),process.platform==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):i.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:i}}var Ce="comet.native.v3",Oe="comet.native.v2",Tt="comet.native.v1",_i="comet.native.transition.v3",Ii="comet.native.transition.v2",er="comet.native.transition.v1";var Uw=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],m_=new Set(Uw),Kw=new Set([...Uw,"minimum_runtime_version","revision"]),v_=new Set([...Kw,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),g_=new Set(["capability","operation","source","base_hash"]),w_=new Set(["shape","build","verify","archive"]),y_=new Set(["implicit","confirmed"]),N_=new Set(["pending","pass","fail"]),$e="comet-state.yaml",Wf=/^[a-f0-9]{64}$/u,Gw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,b_=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,xo=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"},Oi=class extends Error{constructor(i,n){super(i!==Ce||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"},Cn=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"},pi=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"},S_=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
185
+ `);function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Yw(e,t,i){let n=Object.keys(e).filter(r=>!t.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Vt(e){if(!Gw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function k_(e){if(!Gw.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Xw(e,t){if(e.length===0||gt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function E_(e,t){let i=Io(e,`spec_changes[${t}]`);if(Yw(i,g_,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(k_(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"&&Xw(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"||!Wf.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"||!Wf.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 R_(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Uf(e,t){if(Yw(e,t,$e),typeof e.name!="string")throw new Error("Native change name is required");if(Vt(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!w_.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!y_.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(E_),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 e.verification_result!="string"||!N_.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Xw(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!R_(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function jo(e){let t=Io(e,$e);if(t.schema!==Tt)throw new Error(`Expected ${Tt}`);return{schema:Tt,...Uf(t,m_)}}function To(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function zf(e,t,i){if(e===null)return null;let n=typeof e=="string"?b_.exec(e):null;if(!n||n[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function C_(e){if(e==null)return null;if(typeof e!="string"||!Wf.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function P_(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Pn(e){let t=Io(e,$e);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);if(To(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Oe} minimum_runtime_version must be 2`);return{schema:Oe,minimum_runtime_version:2,revision:To(t.revision,"Native v2 revision"),...Uf(t,Kw)}}function _t(e){let t=Io(e,$e);if(t.schema!==Ce){if(t.schema===Tt||t.schema===Oe){let o=t.schema===Tt?jo(t):Pn(t);throw new xo(o.name,o.schema)}throw new Oi(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=To(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Oi(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=To(t.revision,"Native revision"),r=Uf(t,v_),a=C_(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ce,minimum_runtime_version:3,revision:n,verification_protocol:P_(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:zf(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:zf(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:zf(t.partial_allowance,"Native partial_allowance","allowances")}}function A_(e){let t=Io(e,$e);if(t.schema===Tt){let r=jo(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Ce}`}}if(t.schema===Oe){let r=Pn(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Ce}`}}if(t.schema!==Ce){let r=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Oi(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=To(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new Oi(t.schema,i).message};let n=_t(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function Rn(e){let t=_t(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function dl(e){let t=Pn(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function C(e,t){Vt(t);let i=gt.join(e.changesDir,t);if(!$(e.changesDir,i))throw new Error("Native change path escaped");return i}async function tr(e,t){let i=gt.join(C(e,t),"runtime","schema-migration.json");await A(e.nativeRoot,i);try{return await ji.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Kr(e,t){let i=gt.join(C(e,t),"runtime","checkpoint-journal.json");await A(e.nativeRoot,i);try{return await ji.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Qw(e){return re(e.paths,`create change ${e.name}`,()=>x_(e))}async function x_(e){Vt(e.name);let t=e.verificationProtocol??"legacy-v1",i=C(e.paths,e.name);await A(e.paths.nativeRoot,i);let n=!1;try{try{await ji.mkdir(i,{recursive:!1}),n=!0}catch(c){if(c.code==="ENOENT"){await ji.mkdir(e.paths.changesDir,{recursive:!0});try{await ji.mkdir(i,{recursive:!1}),n=!0}catch(l){throw l.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:l}):l}}else throw c.code==="EEXIST"?new Error(`Native change already exists: ${e.name}`,{cause:c}):c}let r={schema:Ce,minimum_runtime_version:3,revision:1,verification_protocol:t,name:e.name,language:e.language,phase:"shape",brief:"brief.md",approval:null,approved_contract_hash:null,spec_changes:[],verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1,created_at:(e.now??new Date).toISOString().slice(0,10),run_id:null};await Promise.all([ji.mkdir(gt.join(i,"specs"),{recursive:!0}),ji.mkdir(gt.join(i,"runtime","checkpoints"),{recursive:!0}),je(gt.join(i,"brief.md"),S_)]);let o=(await le(e.paths.projectRoot))?.native.snapshot??Ic,s=await bo(e.paths,{now:e.now,origin:"change-created",policy:o,limits:{maxFiles:o.max_files,maxFileBytes:o.max_total_bytes,maxTotalBytes:o.max_total_bytes,maxDurationMs:o.max_duration_ms},deadlineMs:o.max_duration_ms});if(!s.complete){let c=el(s),l=s.omitted.reduce((d,f)=>(d[f.reason]=(d[f.reason]??0)+1,d),{}),u=s.omissionOverflow?.count??0;throw u>0&&(l.overflow=u),new pi(r.name,s.omittedCount,l,c.samplePaths,c.sampleTruncated,s.limits,s.policy?.hash??null)}return await tl(e.paths,r.name,s),await I_(e.paths,r),await Ao({paths:e.paths,name:r.name,revision:r.revision,now:e.now}),r}catch(r){throw n&&await ji.rm(i,{recursive:!0,force:!0}),r}}var T_=256*1024;async function Kf(e,t=gt.dirname(e)){let i=gt.relative(t,e).split(gt.sep).join("/"),n=await ge({root:t,ref:i,maxBytes:T_}),r=(0,_o.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${r.errors[0].message}`);return r.toJS()}async function ot(e,t){let i=gt.join(C(e,t),$e);await A(e.nativeRoot,i);let n=A_(await Kf(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await tr(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await __(e,n.state),n)}async function __(e,t){if(await hi(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function W(e,t){let i=await ot(e,t);if(i.status==="migration-required")throw new xo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Oi(i.schema,i.minimumRuntimeVersion);return i.state}async function I_(e,t){let i=gt.join(C(e,t.name),$e);await A(e.nativeRoot,i);try{throw await ji.access(i),new Error(`Native change state already exists: ${t.name}`)}catch(n){if(n.code!=="ENOENT")throw n}if(t.revision!==1)throw new Error("New Native change must start at revision 1");await je(i,(0,_o.stringify)(Rn(t)))}async function Zw(e,t,i){let n={...t,schema:Ce,minimum_runtime_version:3,revision:i+1},r=await tw({expectedRevision:i,next:n,read:async()=>{let a=_t(await Kf(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>je(e,(0,_o.stringify)(Rn(a))),equals:(a,o)=>JSON.stringify(Rn(a))===JSON.stringify(Rn(o)),conflict:a=>new Cn(t.name,i,a)});return Object.assign(t,r),r}async function Gr(e,t,i,n){if(await $r(e.projectRoot),await tr(e,t.name))throw new xo(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await Kr(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await W(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Co(e,t.name);let a=gt.join(C(e,t.name),$e);return await A(e.nativeRoot,a),Zw(a,t,i)}async function ey(e,t){return Zw(e,t,t.revision)}async function ty(e){return _t(await Kf(e))}var ny=["Outcome","Scope","Non-goals","Acceptance examples"],j_=[...ny,"Constraints and invariants","Decisions","Open questions","Verification expectations"],O_=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],ry={maxFileBytes:eo};function ay(e){let t=new Map,i=null,n=[],r=()=>{i!==null&&t.set(i,n.join(`
186
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(r(),i=o[1].trim(),n=[]):i!==null&&n.push(a)}return r(),t}async function oy(e,t){let i=iy.resolve(e,...t.split(/[\\/]/u));if(!$(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await Gf.realpath(e),r=await Gf.realpath(i);if(!$(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Gf.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Oo(e){return{valid:e.length===0,findings:e}}async function ir(e,t){let i=[],n;try{n=(await ge({root:e,ref:t,maxBytes:ry.maxFileBytes})).text}catch(o){return Oo([{code:"brief-missing",message:o.message,path:t}])}let r=ay(n);for(let o of j_)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of ny)(r.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=r.get("Open questions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Oo(i)}async function Yr(e,t){let i=[],n;try{n=(await ge({root:e,ref:t,maxBytes:ry.maxFileBytes})).text}catch(a){return Oo([{code:"verification-missing",message:a.message,path:t}])}let r=ay(n);for(let a of O_)r.has(a)?(r.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Oo(i)}function Jt(e,t){return iy.join(e.specsDir,t,"spec.md")}async function Xr(e,t){let i=[],n=C(e,t.name);for(let r of t.spec_changes){let a=Jt(e,r.capability),o=null;try{await A(e.nativeRoot,a),o=await rt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(r.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${r.capability}`,path:a}),r.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${r.capability}`,path:a}),r.operation!=="create"&&o!==null&&o!==r.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${r.capability}: expected ${r.base_hash}, actual ${o}`,path:a}),r.source)try{await oy(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Oo(i)}async function sy(e,t){return oy(e,t)}import{promises as l$}from"node:fs";import _b from"node:path";import cy from"node:path";import{createHash as $_}from"crypto";function zt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function H_(e,t){t.has(e)&&zt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||zt("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&zt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&zt("symbol properties are not supported"),`[${e.map(n=>Yf(n,t)).join(",")}]`}finally{t.delete(e)}}function D_(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&zt("only plain objects are supported"),t.has(e)&&zt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&zt("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&zt("accessor properties are not supported"),`${JSON.stringify(o)}:${Yf(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Yf(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||zt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?H_(e,t):D_(e,t);case"bigint":case"function":case"symbol":case"undefined":return zt(`${typeof e} values are not supported`)}return zt("unsupported value type")}function $o(e){return Yf(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return $_("sha256").update(`${e}
187
+ ${$o(t)}`).digest("hex")}var M_="comet.native.archive-preflight.v1",F_="comet.native.archive-preflight.v1",L_="comet.native.archive-operation.v1",q_=/^[a-f0-9]{64}$/u,ly=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,B_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function fl(e,t){return e<t?-1:e>t?1:0}function V_(e,t){if(typeof e!="string"||!q_.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $i(e,t){return e===null?null:V_(e,t)}function J_(e,t){let i=cy.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||cy.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function z_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function W_(e,t){if(!ly.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=$i(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=$i(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=$i(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(r===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:n,proposedHash:r}}function U_(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:$i(e.contractHash,"Native archive contract hash"),acceptanceHash:$i(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:$i(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:$i(e.reportHash,"Native archive report hash"),envelopeHash:$i(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:$i(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function K_(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!B_.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(fl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function G_(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(fl)}function uy(e){if(!ly.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(W_).sort((c,l)=>fl(c.capability,l.capability));if(new Set(t.map(c=>c.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(c=>({...c,operationHash:H(L_,c)})),n=U_(e.evidence),r=[...new Set([...K_(e.findingCodes??[]),...G_({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(fl),a=z_(e.revision),o=J_(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let s={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:o,targetExists:e.targetExists,operations:i,evidence:n,findingCodes:r};return{schema:M_,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:a,targetRef:o,ready:r.length===0,evidenceFreshness:n.freshness,operationCount:i.length,operations:i,findingCodes:r,preflightHash:H(F_,s)}}import{createHash as Y_}from"node:crypto";import dy from"node:path";var X_="comet.native.conflict-radar.v1",st=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}),Q_="comet.native.conflict-radar.v1",Z_="comet.native.conflict-radar-signals.v1",eI=/^[a-f0-9]{64}$/u,py=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tI=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),iI=new Set(["capability","operation","baseHash"]),nI=new Set(["path","kind"]);function Qr(e,t){return e<t?-1:e>t?1:0}function Xf(e){return Buffer.byteLength(e,"utf8")}function Qf(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let n=e,r=Object.keys(n).filter(a=>!t.has(a));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);return n}function Zf(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Xf(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function rI(e,t){let i=Zf(e,t,st.maxArtifactPathBytes),n=dy.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||dy.posix.isAbsolute(n)||i.split("/").includes("..")||n!==i||n==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function my(e,t){if(typeof e!="string"||!eI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function aI(e,t){let i=Qf(e,iI,t),n=Zf(i.capability,`${t} capability`,st.maxCapabilityBytes);if(!py.test(n))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let r=i.baseHash===null?null:my(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&r!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&r===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:n,operation:i.operation,baseHash:r}}function oI(e,t){let i=Qf(e,nI,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:rI(i.path,`${t} path`),kind:i.kind}}function sI(e,t){let i=Qf(e,tI,`Conflict radar change ${t}`),n=Zf(i.name,`Conflict radar change ${t} name`,st.maxNameBytes);if(!py.test(n))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${n} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${n} specs must be an array`);if(i.specs.length>st.maxSpecsPerChange)throw new Error(`Conflict radar change ${n} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${n} declared artifacts must be an array`);if(i.declaredArtifacts.length>st.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>aI(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>Qr(c.capability,l.capability));if(new Set(r.map(c=>c.capability)).size!==r.length)throw new Error(`Conflict radar change ${n} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>oI(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>Qr(c.path,l.path)||Qr(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${n} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:my(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function cI(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>st.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(sI).sort((r,a)=>Qr(r.name,a.name));if(new Set(t.map(r=>r.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((r,a)=>r+a.specs.length,0)>st.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>st.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function lI(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function uI(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),n=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),r=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!n&&!r?null:{kind:"artifact",certainty:r?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function dI(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function fI(e,t){let i=[],n=Y_("sha256").update(`${Z_}
188
+ [`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update($o(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<st.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(lI(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=uI(l,u);d&&o(d)}let c=a?"definite-conflict":r>0?"possible-overlap":"disjoint";return n.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:dI(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function fy(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function hI(e,t){return fy(e.classification)-fy(t.classification)||Qr(e.left,t.left)||Qr(e.right,t.right)}function hy(e,t,i,n){let r={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:X_,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:r,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:n}}function eh(e){let t=cI(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(fI(t[s],t[c]));i.sort(hI);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=H(Q_,{changes:t,relationships:n}),a=i.slice(0,st.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=hy(t,i,a,r);for(;a.length>0&&Xf(JSON.stringify(o))>st.maxSerializedBytes;)a=a.slice(0,-1),o=hy(t,i,a,r);if(Xf(JSON.stringify(o))>st.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as nN}from"node:crypto";import{promises as Kt}from"node:fs";import vi from"node:path";import{createHash as Sy}from"node:crypto";import vy from"path";var th="comet.native.implementation-scope.v2",ky="comet.native.content-snapshot-projection.v1",Ho="comet.native.content-snapshot-projection.v1",Ey="comet.native.implementation-scope.v2",pI="comet.native.unresolved-scope-id.v1",mI="comet.native.scope-detail-overflow.v1",vI="comet.native.snapshot-projection-overflow.v2",ah=/^[a-f0-9]{64}$/u,mi=1024*1024,gI=128,wI=128;function Ge(e,t){return e<t?-1:e>t?1:0}function ih(e){if(!ah.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function yI(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function xn(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=vy.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||vy.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Ry(e,t){return e==="."?e:xn(e,t)}function Zr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function NI(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:xn(e.path,`${t} path`),hash:e.hash,size:Zr(e.size,`${t} size`),type:"file"}}function bI(e,t){return{path:Ry(e.path,`${t} path`),size:e.size===null?null:Zr(e.size,`${t} size`),type:e.type,reason:e.reason}}function SI(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function kI(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Do(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
189
189
  `,"utf8")}function An(e,t,i){let n=`${t}
190
- ${$o(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function kI(e){if(Do(e)<=mi)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Sy("sha256");a.update(`${mI}
191
- `),e.omissionOverflow&&An(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,An(a,"omission",f)},s=f=>{n+=1,r+=1,An(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:n===0,entries:t,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Do(u)>mi;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let m=0;m<p;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:r}}}function nh(e){let t=Ti(e),i=t.entries.map((r,a)=>yI(r,`Snapshot entry ${a}`));if(i.sort(bI),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=t.omitted.map((r,a)=>NI(r,`Snapshot omission ${a}`));return n.sort(SI),kI({schema:ky,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function pl(e){let t=new Map;for(let[i,n]of e.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:xn(n.path,`Declared artifact ${i} path`),kind:n.kind},a=t.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);t.set(r.path,r)}return[...t.values()].sort((i,n)=>Ge(i.path,n.path)||Ge(i.kind,n.kind))}function ml(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function gy(e){return e?{hash:e.hash,size:e.size}:null}function Cy(e,t,i){let n=0,r=0;for(;n<e.entries.length||r<t.entries.length;){let a=e.entries[n],o=t.entries[r],s=a===void 0?1:o===void 0?-1:Ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(n+=1),s>=0&&(r+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:gy(c),after:gy(l)})}}function EI(e,t){return{...e,attributedTo:t.filter(i=>ml(i,e.path))}}function Hi(e,t){return{id:`scope:${H(hI,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function RI(e,t){let i=t.omitted.map(n=>Hi({kind:"snapshot-omission",source:e,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${e} snapshot omitted ${n.path}: ${n.reason}`));return t.complete||i.push(Hi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Hi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function wy(e,t){return RI(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function rh(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||wI(e.path,t.path)||Ge(e.id,t.id)}function CI(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(rh)}function PI(e){return[...new Set(e.map((t,i)=>xn(t,`Git path ${i}`)))].sort(Ge)}function Py(e){if(typeof e.contractHash!="string"||!ah.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:pl(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:PI(e.gitChangedPaths)}}}function AI(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Cy(e,t,d=>{let f=i.some(p=>ml(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<vI){let p=EI(d,i),m=Do(p);s+m<=mi?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function Ay(e,t){return Hi({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function xI(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:Zr(Number(t[1]),"Scope overflow change count"),unresolved:Zr(Number(t[2]),"Scope overflow unresolved count"),unattributed:Zr(Number(t[3]),"Scope overflow unattributed count")},n=nr(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Ay(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function TI(e){let t=Sy("sha256");t.update(`${pI}
192
- `);let i=0;Cy(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){An(t,"change",r);let a=0;for(let o of e.declaredArtifacts)ml(o,r.path)&&(a+=1,An(t,"change-attribution",o));An(t,"change-end",{attributionCount:a}),a===0&&An(t,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&An(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function xy(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=AI(e,t,r,i.gitChangedPaths),s=H(Ho,e),c=H(Ho,t),l=[];for(let[w,y]of[["baseline",e],["current",t]])for(let g of y.omitted){if(l.length>=gI)break;l.push(Hi({kind:"snapshot-omission",source:w,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${w} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...wy("baseline",e),...wy("current",t),...o.totalChanges===0&&a===null?[Hi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let w=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(y=>w.has(y)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(y=>!w.has(y))}},p=w=>{let y=o.candidates.slice(0,w.detailedChangeCount),g=y.filter(ii=>ii.attributedTo.length===0),k=o.totalChanges-y.length,x=o.totalUnattributed-g.length,U=u-w.detailedOmissionCount,D=x+U,z=[...g.map(ii=>Hi({kind:"unattributed-change",source:"implementation-scope",path:ii.path,evidence:{after:ii.after,before:ii.before,changeKind:ii.kind}},`Changed path is not covered by a declared artifact: ${ii.path}`)),...l.slice(0,w.detailedOmissionCount),...d,...k>0||D>0?[Ay(w.overflowHash,{changes:k,unattributed:x,unresolved:D})]:[]],ne=CI(z),ti=w.includeGitAdvisory?f():void 0;return{schema:th,contractHash:n,baselineProjectionRef:ih(s),baselineProjectionHash:s,currentProjectionRef:ih(c),currentProjectionHash:c,complete:ne.length===0,declaredArtifacts:r,changes:y,unattributed:g,unresolvedScopes:ne,noCodeReason:a,...ti?{gitAdvisory:ti}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let w=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:b});if(Do({...w,scopeHash:b})<=mi)break;if(v){v=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>m||u>h?TI({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):b,S=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N}),R={...S,scopeHash:H(Ey,S)};if(Do(R)>mi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function Tn(e){let t=nh(e.baseline),i=nh(e.current),n=Py(e);return{authority:n,baseline:t,current:i,scope:xy(t,i,n)}}var _I=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mi(e,t,i,n){let r=new Set([...t,...i]),a=Object.keys(e).filter(s=>!r.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function nr(e,t){if(typeof e!="string"||!ah.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yy(e,t,i){let n=ih(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function ea(e,t){let i=Di(e,"Native snapshot projection");if(Mi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==ky)throw new Error("Native snapshot projection schema is invalid");let n=Ti({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=nh(n);if(H(Ho,i)!==H(Ho,r))throw new Error("Native snapshot projection is not canonical");let a=H(Ho,r);if(t!==void 0&&nr(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function oh(e,t){let i=Di(e,`Declared artifact ${t}`);if(Mi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:xn(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Ny(e,t){if(e===null)return null;let i=Di(e,t);return Mi(i,["hash","size"],[],t),{hash:nr(i.hash,`${t} hash`),size:Zr(i.size,`${t} size`)}}function by(e,t){let i=Di(e,`Implementation change ${t}`);if(Mi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let n=i.attributedTo.map(oh),r=pl(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Ny(i.before,`Implementation change ${t} before`),o=Ny(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:xn(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function II(e,t){let i=Di(e,`Unresolved scope ${t}`);Mi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Ry(i.path,`Unresolved scope ${t} path`):xn(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function hl(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((r,a)=>xn(r,`${t} ${a}`)),n=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function ta(e){let t=Di(e,"Native implementation scope"),i=[..._I].filter(y=>y!=="gitAdvisory");if(Mi(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==th)throw new Error("Native implementation scope schema is invalid");let n=nr(t.contractHash,"Implementation scope contractHash"),r=nr(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=yy(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=nr(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=yy(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(oh);if(JSON.stringify(c)!==JSON.stringify(pl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(by),u=[...l].sort((y,g)=>Ge(y.path,g.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(g=>ml(g,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(by),p=l.filter(y=>y.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(II),h=m.filter(y=>y.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:xI(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let b=t.noCodeReason,E=[...p.map(y=>Hi({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(v?.changes??0)===0&&b===null?[Hi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],N=m.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(rh))||new Set(m.map(y=>y.id)).size!==m.length||JSON.stringify(N)!==JSON.stringify(E.sort(rh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let y=Di(t.gitAdvisory,"Implementation scope Git advisory");if(Mi(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=hl(y.changedPaths,"Git changed paths"),k=hl(y.pathsPresentInSnapshotChanges,"Git present paths"),x=hl(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),U=[...k,...x].sort(Ge),D=new Set(l.map(z=>z.path));if(JSON.stringify(U)!==JSON.stringify(g)||(v?.changes??0)===0&&k.some(z=>!D.has(z))||x.some(z=>D.has(z)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:k,pathsAbsentFromSnapshotChanges:x}}let R={schema:th,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:b,...S?{gitAdvisory:S}:{}},w=nr(t.scopeHash,"Implementation scope scopeHash");if(H(Ey,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function jI(e){let t=Di(e,"Native implementation scope authority");if(Mi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(oh);if(JSON.stringify(i)!==JSON.stringify(pl(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;t.gitChangedPaths!==void 0&&(n=hl(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Py({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Wt(e){let t=Di(e,"Native implementation scope bundle");Mi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=jI(t.authority),n=ea(t.baseline),r=ea(t.current),a=ta(t.scope),o=xy(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function Ty(e){let t=ta(e.scope);return Wt({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import _y from"node:path";var OI=/\b(Bearer|Basic)\s+[^\s"']+/giu,$I=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,HI=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,DI=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,MI=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,FI=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,LI=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Ne(e){return e.replace(OI,"$1 [REDACTED]").replace($I,"[REDACTED PRIVATE KEY]").replace(HI,"$1[REDACTED]@").replace(DI,"[REDACTED TOKEN]").replace(MI,'$1"[REDACTED]"').replace(FI,"$1$2$1$3$4[REDACTED]$4").replace(LI,"$1$2[REDACTED]")}var Iy=/^[a-f0-9]{64}$/u,qI=8,jy="comet.native.acceptance-trace.v2",Oy="comet.native.partial-allowance.v1",$y="comet.native.verification-evidence.v2";function It(e,t){if(!Iy.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yl(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Nl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function ia(e,t,i=2e3){let n=Ne(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function _n(e,t){let i=_y.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||_y.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function Hy(e,t,i){let n=_n(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=ai(n),a=n.toLowerCase(),o=i?_n(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Mo(e){let t=_n(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Dy(e){let t=e.toISOString();if(Number.isNaN(Date.parse(t)))throw new Error("Native evidence timestamp is invalid");return t}function BI(e){return H("comet.native.acceptance-set.v1",[...e].sort((t,i)=>jt(t.id,i.id)))}function jt(e,t){return e<t?-1:e>t?1:0}function My(e,t,i){let n=_n(i.nativeRootRef,"Native root ref"),r=new Map(e.map(u=>[u.id,u]));if(r.size!==e.length)throw new Error("Native contract has duplicate acceptance IDs");let a=new Map;for(let u of t){if(!r.has(u.acceptance_id))throw new Error(`Verification references unknown acceptance ID: ${u.acceptance_id}`);if(a.has(u.acceptance_id))throw new Error(`Verification repeats acceptance ID: ${u.acceptance_id}`);a.set(u.acceptance_id,u)}let o=[...r.keys()].filter(u=>!a.has(u));if(o.length>0&&i.allowMissing!==!0){let u=o.slice(0,qI),d=o.length-u.length;throw new Error(`Verification is missing ${o.length} acceptance evidence entr${o.length===1?"y":"ies"}: ${u.join(", ")}${d>0?`, ... (${d} more)`:""}`)}let s=[...r.values()].sort((u,d)=>jt(u.id,d.id)).map(u=>{let d=a.get(u.id);if(!d)return{acceptanceId:u.id,status:"missing",kind:u.kind,source:_n(u.source,`Acceptance source for ${u.id}`),evidenceRefs:[],skippedReason:null};let f=d.status,p=[...d.evidence_refs].map(v=>Mo(v)).sort();if(new Set(p).size!==p.length)throw new Error(`Verification repeats an evidence ref for ${u.id}`);let m=d.skipped_reason?.trim()||null,h=m===null?null:ia(m,`Skipped reason for ${u.id}`);if(f==="passed"&&(p.length===0||h!==null)||f==="failed"&&p.length===0&&h===null)throw new Error(`Acceptance ${u.id} has an invalid evidence state`);return{acceptanceId:u.id,status:f,kind:u.kind,source:_n(u.source,`Acceptance source for ${u.id}`),evidenceRefs:p,skippedReason:h}}),c=BI(e),l={schema:"comet.native.acceptance-trace.v2",nativeRootRef:n,criteriaHash:c,total:s.length,evidenced:s.filter(u=>u.evidenceRefs.length>0).length,skipped:s.filter(u=>u.skippedReason!==null).length,entries:s};return{...l,traceHash:H(jy,l)}}function Fy(e){let t=Wt(e.scopeBundle).scope;if(t.complete)throw new Error("Complete implementation scope cannot be partially allowed");let i=new Set(t.unresolvedScopes.map(s=>s.id));if(new Set(e.allowedScopeIds).size!==e.allowedScopeIds.length)throw new Error("Partial allowance has duplicate allowed scope IDs");let n=[...e.allowedScopeIds].sort(jt);if(n.length===0)throw new Error("Partial allowance requires at least one scope ID");if([...i,...n].some(s=>!/^scope:[a-f0-9]{64}$/u.test(s)))throw new Error("Partial allowance scope IDs are invalid");let r=n.filter(s=>!i.has(s)),a=[...i].filter(s=>!n.includes(s));if(r.length>0)throw new Error(`Partial allowance has unknown scope IDs: ${r}`);if(a.length>0)throw new Error(`Partial allowance is missing scope IDs: ${a}`);let o={schema:"comet.native.partial-allowance.v1",change:Nl(e.change),scopeHash:t.scopeHash,scopeIds:n,reason:ia(e.reason,"Partial allowance reason"),confirmedSummary:ia(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:yl(e.sourceRevision),confirmedAt:Dy(e.now??new Date)};return{...o,allowanceHash:H(Oy,o)}}function Ly(e){if(e.result!=="pass"&&e.result!=="fail")throw new Error("Native verification evidence result is invalid");let t=By(e.acceptanceTrace),i=Wt(e.implementationScope.bundle).scope,n=wl(e.implementationScope.ref,"scopes",i.scopeHash);if(i.contractHash!==e.contractHash)throw new Error("Implementation scope does not match the verification contract");let r=e.partialAllowance??null,a=r?Fo(r.allowance):null,o=r&&a?{ref:wl(r.ref,"allowances",a.allowanceHash),allowance:a}:null;if(i.complete&&o!==null)throw new Error("Complete implementation scope must not use a partial allowance");if(!i.complete&&o===null)throw new Error("Partial implementation scope requires a confirmed allowance");let s=i.unresolvedScopes.map(f=>f.id).sort(jt);if(o&&(o.allowance.change!==e.change||o.allowance.scopeHash!==i.scopeHash||JSON.stringify(o.allowance.scopeIds)!==JSON.stringify(s)))throw new Error("Partial allowance does not match the verification scope");if(t.criteriaHash!==e.acceptanceHash)throw new Error("Acceptance trace does not match the verification contract");if(o&&o.allowance.sourceRevision>=e.sourceRevision)throw new Error("Partial allowance must precede the verification evidence revision");let c=[...new Set(t.entries.flatMap(f=>f.evidenceRefs))].sort(jt),l=[...new Set(e.requiredReceiptRefs.map(Mo))].sort(jt),u=c;if(e.result==="pass"&&l.length===0)throw new Error("Passing verification requires at least one current required check receipt");let d={schema:"comet.native.verification-evidence.v2",change:Nl(e.change),sourceRevision:yl(e.sourceRevision),result:e.result,freshness:i.complete?"complete":"partial",contractHash:It(e.contractHash,"Verification contractHash"),acceptanceCriteriaHash:It(e.acceptanceHash,"Verification acceptanceHash"),implementationScopeRef:n,implementationScopeHash:i.scopeHash,reportRef:Hy(e.reportRef,"Verification report ref"),reportHash:It(e.reportHash,"Verification report hash"),acceptanceTrace:t,partialAllowanceRef:o?.ref??null,partialAllowanceHash:o?.allowance.allowanceHash??null,requiredReceiptRefs:l,receiptRefs:u,createdAt:Dy(e.now??new Date)};return{...d,envelopeHash:H($y,d)}}function vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gl(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function qy(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function wl(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let n=`runtime/evidence/${t}/${i}.json`;if(e!==n)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function By(e){let t=vl(e,"Native acceptance trace");if(gl(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Iy.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=_n(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=vl(o,`Native acceptance trace entry ${s}`);if(gl(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Mo(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(jt))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:_n(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:ia(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>jt(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||t.total!==n.length||t.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:n},a=It(t.traceHash,"Native acceptance trace hash");if(H(jy,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Fo(e){let t=vl(e,"Native partial allowance");if(gl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(jt))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Nl(t.change),scopeHash:It(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:ia(t.reason,"Partial allowance reason"),confirmedSummary:ia(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:yl(t.sourceRevision),confirmedAt:qy(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=It(t.allowanceHash,"Native partial allowance hash");if(H(Oy,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function na(e){let t=vl(e,"Native verification evidence");if(gl(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=It(t.implementationScopeHash,"Native verification implementation scope hash"),n=By(t.acceptanceTrace),r=It(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:It(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Mo(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(jt)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(jt);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Mo(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(jt)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Nl(t.change),sourceRevision:yl(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:It(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:wl(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:Hy(t.reportRef,"Native verification report ref"),reportHash:It(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:wl(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:qy(t.createdAt,"Native verification timestamp")},d=It(t.envelopeHash,"Native verification envelope hash");if(H($y,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Vy from"node:path";var bl="comet.native.check-receipt.v1",Wy="comet.native.check-receipt.v1",In="scoped-text-safety",Lo=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),VI=/^[a-f0-9]{64}$/u,JI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zI="comet.native.checker-policy.v1",WI="comet.native.check-input.v1",UI=2048,Sl=H(zI,{policy:In,version:Lo,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),KI=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Jy=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Uy=["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"],GI=new Set(Uy);function ar(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function or(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Fi(e,t){if(typeof e!="string"||!VI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Ky(e,t){let i=rr(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function zy(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function YI(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>UI||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Vy.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Vy.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function XI(e){let t=ar(e,"Native check receipt checker");or(t,["policy","version","hash","limits"],"Native check receipt checker");let i=ar(t.limits,"Native check receipt limits");if(or(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==In||t.version!==Lo||t.hash!==Sl||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:In,version:Lo,hash:Sl,limits:{...Pe}}}function QI(e){let t=ar(e,"Native check receipt contract");return or(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Fi(t.expectedHash,"Native check expected contract hash"),beforeHash:Fi(t.beforeHash,"Native check before contract hash"),afterHash:Fi(t.afterHash,"Native check after contract hash")}}function ZI(e){let t=ar(e,"Native check receipt implementation");return or(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Fi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Fi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Fi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Fi(t.afterSnapshotHash,"Native check after snapshot hash")}}function ej(e){let t=ar(e,"Native check receipt counts");or(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:rr(t.filesSelected,"Native check filesSelected"),filesScanned:rr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:rr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:rr(t.bytesScanned,"Native check bytesScanned"),issueCount:rr(t.issueCount,"Native check issueCount"),recordedIssueCount:rr(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function tj(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Jy.indexOf(e.kind)-Jy.indexOf(t.kind)}function ij(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=ar(n,`Native check issue ${r}`);if(or(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!KI.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:YI(a.path,`Native check issue ${r} path`),line:Ky(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(tj);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function nj(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!GI.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Uy.filter(n=>t.includes(n));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function Gy(e){return H(WI,e)}function Li(e){let t=ar(e,"Native check receipt");if(or(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==bl)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!JI.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Ky(t.sourceRevision,"Native check source revision"),n=XI(t.checker),r=QI(t.contract),a=ZI(t.implementation),o=Gy({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Fi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=zy(t.startedAt,"Native check receipt startedAt"),c=zy(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=ej(t.counts),u=ij(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=nj(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Pe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:bl,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=Fi(t.receiptHash,"Native check receipt content hash");if(H(Wy,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}function Yy(e){let t={policy:In,version:Lo,hash:Sl,limits:{...Pe}},i={schema:bl,...e,checker:t,inputHash:Gy({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return Li({...i,receiptHash:H(Wy,i)})}var kl="comet.native.verification-receipt.v3",Xy=kl,rj="comet.native.declared-artifacts.v1",aj=/^[a-f0-9]{64}$/u,oj=/^acceptance-[a-f0-9]{64}$/u,sj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,cj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,lj=4096,uj=256,dj=1024;function ra(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function jn(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function qi(e,t){if(typeof e!="string"||!aj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ut(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Ne(e).trim();if(!i||i.length>lj||i!==e.trim())throw new Error(`${t} is invalid`);return i}function sh(e,t){let i=Ut(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function qo(e,t,i=Ut,n=!1,r=uj){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function fj(e,t){if(typeof e!="string"||!oj.test(e))throw new Error(`${t} is invalid`);return e}function hj(e){let t=ra(e,"Native verification receipt bindings");if(jn(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!sj.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:qi(t.contractHash,"Native verification receipt contract hash"),scopeHash:qi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:qi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:qi(t.artifactHash,"Native verification receipt artifact hash")}}function pj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=cj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function mj(e,t,i,n){let r=ra(t,`Native ${e} evidence`);if(e==="automated-check"){if(jn(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=sh(r.startedAt,"Native automated-check start time"),o=sh(r.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&r.exitCode!==0||i==="failed"&&r.exitCode===0||i==="passed"&&(r.timedOut||r.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ra(r.worktree,"Native automated-check worktree");if(jn(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=ra(r.afterFence,"Native automated-check after fence");if(jn(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ut(r.executable,"Native automated-check executable"),args:qo(r.args,"Native automated-check arguments",Ut,!0),cwd:Ut(r.cwd,"Native automated-check cwd"),exitCode:r.exitCode,signal:r.signal,timedOut:r.timedOut,timeoutMs:r.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ut(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:qi(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:qi(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:qi(r.outputHash,"Native automated-check output hash"),outputSummary:Ut(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){jn(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=pj(r.checkReceiptRef);if(qi(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:qo(r.subjects,"Native static inspection subjects",Ut,n==="required-check"),rule:Ut(r.rule,"Native static inspection rule"),resultSummary:Ut(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jn(r,["steps","observations"],"Native manual-evidence evidence"),{steps:qo(r.steps,"Native manual evidence steps"),observations:qo(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Qy(e){let t=ra(e,"Native verification receipt");if(jn(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,n=t.role,r=t.status,a=Ut(t.actor,"Native verification receipt actor"),o=qo(t.acceptanceIds,"Native receipt acceptance IDs",fj,n==="required-check",dj).sort();if(n==="required-check"&&o.length!==0||n==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(n==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:kl,kind:i,role:n,status:r,bindings:hj(t.bindings),acceptanceIds:o,actor:a,issuedAt:sh(t.issuedAt,"Native verification receipt issue time"),evidence:mj(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==In||s.actor!==`native-runtime:${In}`))throw new Error("Native required check policy identity is invalid");return s}function El(e){let t=Qy({schema:kl,...e});return{...t,receiptHash:H(Xy,t)}}function Bo(e){let t=ra(e,"Native verification receipt");if(jn(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==kl)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=Qy(n),a=qi(t.receiptHash,"Native verification receipt hash");if(H(Xy,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function Rl(e){return H(rj,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}function Zy(e){return e.kind==="static-inspection"?`static:${e.evidence.rule}`:e.kind==="automated-check"?`automated:${H("comet.native.failed-check.v1",{executable:e.evidence.executable,args:e.evidence.args,acceptanceIds:e.acceptanceIds})}`:`manual:${H("comet.native.failed-check.v1",{acceptanceIds:e.acceptanceIds})}`}var rN=/^[a-f0-9]{64}$/u,Gt=mi,wB=3*Gt;function ch(e,t){let i=vi.relative(e,t);return i===""||!vi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vi.sep}`)}function vj(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function eN(e){let t=await Kt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Kt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function gj(e,t){let i=vi.resolve(e),n=vi.resolve(t);if(!ch(i,n))throw new Error("Native evidence path is outside its change");let r=[await eN(i)],a=i;for(let o of vi.relative(i,n).split(vi.sep).filter(Boolean)){a=vi.join(a,o);let s=await eN(a);if(!ch(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function tN(e){for(let t of e){let i=await Kt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!vj(t,i)||await Kt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function wj(e,t,i={}){let n=await gj(t,vi.dirname(e));await i.afterParentChainCaptured?.();let r=await Kt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Kt.realpath(e);if(!ch(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Kt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Kt.lstat(e),Kt.realpath(e)]);if(await tN(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Cl(s,r)||!Cl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Gt)throw new Error(`Native evidence document exceeds ${Gt} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Gt+1-d,b=await o.read(f,0,Math.min(f.length,v),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>Gt)throw new Error(`Native evidence document exceeds ${Gt} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Kt.lstat(e),Kt.realpath(e)]);if(await tN(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Cl(s,p)||!Cl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function wt(e,t){if(!rN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function aN(e){return wt("reports",e)}async function oN(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Gt||nN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return sr({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function yj(e,t,i,n,r){if(!rN.test(i))throw new Error("Native report evidence hash is invalid");let a=await Bi({paths:e,name:t,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||nN("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function aa(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function sN(e,t,i,n,r){return vi.join(r??C(e,t),...wt(i,n).split("/"))}async function Bi(e){let t=e.changeDir??C(e.paths,e.name),i=sN(e.paths,e.name,e.kind,e.hash,t);return await A(e.paths.nativeRoot,i),wj(i,t,e.hooks)}async function sr(e){Pl(e.value);let t=sN(e.paths,e.name,e.kind,e.hash);await A(e.paths.nativeRoot,t);try{let n=await Bi(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return wt(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await de(t,e.value,{containedRoot:e.paths.nativeRoot});let i=await Bi(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return wt(e.kind,e.hash)}function Pl(e){if(Nj(e)>Gt)throw new Error(`Native evidence document exceeds ${Gt} bytes`)}function Nj(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
193
- `,"utf8")}function iN(e,t){return ea(e,t)}function bj(e,t){let i=ta(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function cN(e,t,i){let n=Fo(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function lN(e,t,i){let n=na(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function uN(e,t,i,n=!1,r){let a=await Al(e,t,i.implementationScopeRef,void 0,r);if(n&&await yj(e,t,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await lh(e,t,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function dN(e){let t=Wt(e.bundle),{baseline:i,current:n,scope:r}=t;return Pl(i),Pl(n),Pl(r),await sr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.baselineProjectionHash,value:i}),await sr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.currentProjectionHash,value:n}),sr({paths:e.paths,name:e.name,kind:"scopes",hash:r.scopeHash,value:r})}async function gi(e,t,i,n,r){let a=aa(i,"scopes"),o=bj(await Bi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=aa(o.baselineProjectionRef,"snapshots"),c=aa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Bi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>iN(d,s)),Bi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>iN(d,c))]);return Ty({baseline:l,current:u,scope:o})}async function Al(e,t,i,n,r){return(await gi(e,t,i,n,r)).scope}async function fN(e){let t=cN(e.allowance,e.name,e.allowance.allowanceHash),i=await Al(e.paths,e.name,wt("scopes",t.scopeHash)),n=i.unresolvedScopes.map(r=>r.id).sort();if(i.complete||JSON.stringify(n)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return sr({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function lh(e,t,i,n,r){let a=aa(i,"allowances");return cN(await Bi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function xl(e){let t=Bo(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return sr({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function oa(e,t,i,n,r){let a=aa(i,"receipts"),o=Bo(await Bi({paths:e,name:t,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function hN(e){let t=lN(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await uN(e.paths,e.name,t,!0),sr({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function On(e,t,i,n,r){let a=aa(i,"verifications"),o=lN(await Bi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await uN(e,t,o,!1,r),o}async function Sj(e){try{let t=await pt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:st.maxChanges});return await t.verify(),t.entries}catch(t){if(t.code==="ENOENT")return[];throw t}}async function kj(e,t){let i=await W(e,t),[n,r]=await Promise.all([i.implementation_scope?Al(e,t,i.implementation_scope):null,ul(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:n?.declaredArtifacts??[],workspaceIdentityHash:r?.nativeRootId??null}}async function Ej(e){let i=(await Sj(e)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();return Promise.all(i.map(n=>kj(e,n)))}async function Tl(e,t){let i=await Ej(e);eh(i);let n=i.find(o=>o.name===t);if(!n)throw new Error(`Native conflict target is not visible: ${t}`);let r=0,a=0;for(let o of i){if(o.name===t)continue;let s=eh([n,o]).relationships[0];s.classification==="definite-conflict"&&(r+=1),s.classification==="possible-overlap"&&(a+=1)}return{definiteConflictCount:r,possibleOverlapCount:a,findingCodes:[...r>0?["native-change-conflict"]:[],...a>0?["native-change-overlap"]:[]]}}import{randomUUID as Uj}from"crypto";import{promises as Kj}from"fs";import Gj from"path";import{isDeepStrictEqual as vh}from"util";var Rj="comet.native.repair-signature.v1",yt={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3},Cj="comet.native.repair-signature.v1",Pj="comet.native.repair-override-summary.v1",Aj=/^[a-f0-9]{64}$/u,xj=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function mN(e,t){return e<t?-1:e>t?1:0}function _l(e,t){if(typeof e!="string"||!Aj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uh(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Il(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!xj.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(mN)}function sa(e=[]){return Il(e,"Native repair failed check IDs",yt.maxFailedCheckIds,!0)}function vN(e){let t=sa(e.failedCheckIds),i=Il(e.failedAcceptanceIds,"Native repair failed acceptance IDs",yt.maxFailedAcceptanceIds,!0),n={schema:Rj,contractHash:_l(e.contractHash,"Native repair contract hash"),failedAcceptanceIds:i,failedCheckIds:t};return{...n,signatureHash:H(Cj,n)}}function Tj(e){if(!Array.isArray(e)||e.length>yt.maxHistoryRecords)throw new Error("Native repair history exceeds its record boundary");let t=0,i=0;return e.map((n,r)=>{if(!n||n.kind!=="failure"&&n.kind!=="override")throw new Error(`Native repair history record ${r} is invalid`);let a=n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?["iteration","kind","revision","signatureHash"]:["failedAcceptanceIds","failedCheckIds","iteration","kind","revision","signatureHash"]:["iteration","kind","revision","signatureHash","summaryHash"],o=Object.keys(n).sort(mN);if(o.length!==a.length||o.some((f,p)=>f!==a[p]))throw new Error(`Native repair history record ${r} fields are invalid`);let s=uh(n.iteration,`Native repair history ${r} iteration`),c=uh(n.revision,`Native repair history ${r} revision`),l=r>0?e[r-1]:null;if(!(n.kind==="override"&&l?.kind==="failure"&&s===t&&c>=i&&n.signatureHash===l.signatureHash)&&(s<=t||c<=i))throw new Error("Native repair history must be strictly ordered by revision and iteration");t=s,i=c;let d=_l(n.signatureHash,`Native repair history ${r} signature`);return n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?{kind:"failure",iteration:s,revision:c,signatureHash:d}:{kind:"failure",iteration:s,revision:c,signatureHash:d,failedAcceptanceIds:Il(n.failedAcceptanceIds??[],`Native repair history ${r} failed acceptance IDs`,yt.maxFailedAcceptanceIds,!0),failedCheckIds:Il(n.failedCheckIds??[],`Native repair history ${r} failed check IDs`,yt.maxFailedCheckIds,!0)}:{kind:"override",iteration:s,revision:c,signatureHash:d,summaryHash:_l(n.summaryHash,`Native repair history ${r} summary`)}})}function pN(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function _j(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:pN(e.failedAcceptanceIds,t.failedAcceptanceIds)&&pN(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Vo(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(_j(n,a))break;i+=1,n=a}return i}function gN(e){let t=e.trim();if(t.length===0||t.length>yt.maxOverrideSummaryCharacters)throw new Error("Native repair override summary is invalid");return t}function jl(e){return H(Pj,{summary:gN(e)})}function wN(e){let t=vN(e.facts),i=Tj(e.history),n=i.filter(l=>l.kind==="failure"),r=n.length+1,a=uh(e.maxVerifyFailures,"Native maximum Verify failures"),o=Math.max(0,a-r),s=Vo({signatureHash:t.signatureHash,failedAcceptanceIds:t.failedAcceptanceIds,failedCheckIds:t.failedCheckIds},n);if(r>=a)return{disposition:"hard-stop",reasonCode:"repair-iteration-limit",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(s<yt.warningAtConsecutiveFailures)return{disposition:"continue",reasonCode:"new-failure-signature",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(s<yt.manualStopAtConsecutiveFailures)return{disposition:"warn",reasonCode:"repeated-failure-warning",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(e.override){if(_l(e.override.expectedSignatureHash,"Native repair override expected signature")!==t.signatureHash)throw new Error("Native repair override does not match the current failure signature");gN(e.override.summary);let u=i.some(d=>d.kind==="override"&&d.signatureHash===t.signatureHash);return{disposition:u?"manual-stop":"continue",reasonCode:u?"override-already-used":"override-accepted",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!u}}return{disposition:"manual-stop",reasonCode:i.some(l=>l.kind==="override"&&l.signatureHash===t.signatureHash)?"override-already-used":"repeated-failure-stop",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1}}function $n(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var yN="repairStagnation",Nt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},jj=/^[a-f0-9]{64}$/u,NN="comet.native.repair-scope.v1",Oj=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),$j=["data","runId","sequence","timestamp","type"],bN=["disposition","overrideSummaryHash","signatureHash"],Hj=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],SN=12;function Ol(e,t){return e<t?-1:e>t?1:0}function fh(e,t,i){let n=Object.keys(e).sort(Ol);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function Jo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function ca(e,t){if(typeof e!="string"||!jj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Dj(e){if(!Array.isArray(e)||e.length>yt.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Ol)}function la(e){let t=Wt(e).scope;return H(NN,{schema:NN,contractHash:t.contractHash,artifactSnapshotHash:t.currentProjectionHash})}function kN(e){if(typeof e!="string"||e.length===0||e.length>Nt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function dh(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Nt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Nt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Nt.maxTextCharacters&&(!r||e.length>Nt.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${n} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${n} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Nt.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>dh(s,t+1,i,`${n}[${c}]`));return}let a=Jo(e,n),o=Object.keys(a);if(o.length>Nt.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Nt.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");dh(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function Mj(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function Fj(e,t,i){let n=Jo(e,`Native repair trajectory event ${t+1}`);if(fh(n,$j,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(Mj(n.timestamp),typeof n.type!="string"||!Oj.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(kN(n.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let r={nodes:0,characters:0,ancestors:new Set};return dh(n.data,0,r,"Native trajectory event data"),Jo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function hh(e){let t=Jo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Ol),n=i.length===bN.length&&i.every((l,u)=>l===bN[u]);n||fh(t,Hj,"Native repair trajectory projection");let r=ca(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:ca(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=ca(t.contractHash,"Native repair trajectory contract hash"),s=Dj(t.failedAcceptanceIds),c=sa(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function Lj(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function qj(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??SN;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Vo({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<yt.warningAtConsecutiveFailures?"continue":a<yt.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function Bj(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??SN;if(n.length>=r)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||n.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function $l(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Nt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=kN(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],n=null,r=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=Fj(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Nt.maxTotalDataNodes||c>Nt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?ca(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?ca(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,yN)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&r!==null&&p!==r||p===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=hh(f[yN]);if(Lj(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&p!==null&&r!==null&&p!==r&&(i.length=0,o=0),p!==null&&(r=p),qj(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(n?.contractHash===null&&p!==null&&r!==null&&p!==r)throw new Error("Native repair override cannot cross implementation scope progress");Bj(m,i,n);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>yt.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function EN(e){return $l(e).history}function RN(e){let t=$l(e).latestProjection;return t?{...t}:null}function CN(e){let t=$l(e),i=Jo(e.override,"Native repair override request");fh(i,["expectedSignatureHash","summary"],"Native repair override request");let n=ca(i.expectedSignatureHash,"Native repair override expected signature");if(typeof i.summary!="string")throw new Error("Native repair override summary is invalid");if(t.latestProjection?.disposition==="hard-stop")throw new Error("Native repair hard stop cannot be overridden");if(t.latestProjection?.disposition!=="manual-stop"||t.latestProjection.signatureHash!==n)throw new Error("Native repair override does not match the latest manual stop");if(t.history.some(a=>a.kind==="override"&&a.signatureHash===n))throw new Error("Native repair signature was already overridden");let r=jl(i.summary);return{history:t.history,eventProjection:{signatureHash:n,disposition:"continue",overrideSummaryHash:r,contractHash:t.latestProjection.contractHash,failedAcceptanceIds:[...t.latestProjection.failedAcceptanceIds],failedCheckIds:[...t.latestProjection.failedCheckIds],maxVerifyFailures:t.latestProjection.maxVerifyFailures}}}function Vj(e){let t=na(e.envelope),i=Wt(e.implementationScope);if(t.result!=="fail")throw new Error("Native repair stagnation requires a failed verification envelope");if(t.contractHash!==i.scope.contractHash||t.implementationScopeHash!==i.scope.scopeHash)throw new Error("Native repair evidence does not match the implementation scope authority");return{contractHash:i.scope.contractHash,implementationScopeHash:la(i),artifactSnapshotHash:i.scope.currentProjectionHash,failedAcceptanceIds:t.acceptanceTrace.entries.filter(n=>n.status==="failed"||n.status==="missing").map(n=>n.acceptanceId).sort(Ol),failedCheckIds:sa(e.failedCheckIds)}}function Jj(e,t){return{signatureHash:e.signature.signatureHash,disposition:e.disposition,overrideSummaryHash:t,contractHash:e.signature.contractHash,failedAcceptanceIds:[...e.signature.failedAcceptanceIds],failedCheckIds:[...e.signature.failedCheckIds],maxVerifyFailures:e.totalRepairFailures+e.remainingIterations}}function zj(e){let t=Vj(e),i=$l(e);return{facts:t,history:i.latestProjection?.contractHash!==null&&i.latestProjection?.contractHash!==t.contractHash?[]:i.history}}function PN(e){let t=zj(e),i=wN({...t,maxVerifyFailures:e.maxVerifyFailures});return{...t,decision:i,eventProjection:Jj(i,null)}}var ct={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:[]},cr=F("comet-native-runtime:v3:semantic-repair-budget"),Wj=[{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function AN(e){return e.skillVersion===ct.definition.metadata.version&&e.skillHash===cr||Wj.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var ua={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Hn(e){let i={sequence:(await qe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await $w(e.changeDir,e.run.trajectoryRef,i),i}async function lr(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Hw(e.changeDir,e.run.checkpointRef,t),t}function Hl(e){return F(JSON.stringify({summary:e.summary,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var HN=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Yj=new Set(HN),DN=new Set([...HN,"minimum_runtime_version","revision"]),Xj=new Set([...DN,"operation"]),Qj=512*1024,ph=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Zj=new Set([...ph,"implementationScopeHash","repairScopeHash","repairStagnation"]),zo=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Be(e,t){return Gj.join(C(e,t),"runtime","transition.json")}function eO(e){return`transition-${e}`}async function tO(e,t,i){let n=eO(t);return ci(e,n,i)}async function He(e,t,i,n){let r=await tO(e,t,i);try{return await n()}finally{await li(r)}}function Ml(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function gh(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Dl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function wi(e,t){return vh(e,t)}function mh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(u=>!Zj.has(u)),a=[...ph].find(u=>!Object.hasOwn(i,u)),o=ph.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if($n(i.summary,"Native transition journal event summary"),Ne(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&($n(i.noCodeReason,"Native transition journal event no-code reason"),Ne(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?hh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function iO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return mh({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return mh(e,t)}function wh(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?iO(e.eventData,e.evidenceHash):mh(e.eventData,e.evidenceHash),r=kn(e.nextRun),a=e.previousRun===null?null:kn(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function xN(e,t,i=!1){if(e.skill!==ct.definition.metadata.name||(i?!AN(e):e.skillVersion!==ct.definition.metadata.version||e.skillHash!==cr)||e.orchestration!==ct.definition.orchestration.mode||e.pendingRef!==at.pendingRef||e.trajectoryRef!==at.trajectoryRef||e.contextRef!==at.contextRef||e.artifactsRef!==at.artifactsRef||e.checkpointRef!==at.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function TN(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function _N(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function yh(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(xN(a,"next Run",n||r!==null),_N(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(xN(r,"previous Run",!0),_N(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!vh(TN(r),TN(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function nO(e,t,i){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function MN(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function IN(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Nh(e,t,i,n,r=!1){let a=i.eventData,o=IN(e),s=IN(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&vh(e.spec_changes,t.spec_changes),l=Hl({summary:a.summary});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=nO(e.name,a.summary,t.spec_changes),l=F(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Fl(e,t){let i=Ml(e);if(gh(i,Xj),i.schema!==_i)throw new Error(`Expected Native transition schema ${_i}`);let n=Dl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${_i} minimum_runtime_version must be ${3}`);let r=Dl(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=wh(i,t),o=_t(i.previousState),s=_t(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Nh(o,s,a,i.operation),yh(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:_i,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function rO(e,t){let i=Ml(e);if(gh(i,Yj),i.schema!==er)throw new Error(`Expected Native transition schema ${er}`);let n=wh(i,t,!0),r=jo(i.previousState),a=jo(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Nh(r,a,n,MN(r,a,n.eventData),!0),yh(r,a,n,!0),{schema:er,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function bh(e,t){let i=Ml(e);if(gh(i,DN),i.schema!==Ii)throw new Error(`Expected Native transition schema ${Ii}`);if(Dl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ii} minimum_runtime_version must be 2`);let r=Dl(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=wh(i,t,!0),o=Pn(i.previousState),s=Pn(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Nh(o,s,a,MN(o,s,a.eventData),!0),yh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ii,minimum_runtime_version:2,revision:r,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function aO(e,t){let i=Ml(e);if(i.schema===_i)return{status:"current",journal:Fl(i,t)};if(i.schema===er)return{status:"migration-required",journal:rO(i,t)};if(i.schema===Ii)return{status:"migration-required",journal:bh(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Sh(e,t){let i=Be(e,t);await A(e.nativeRoot,i);try{let n=await ue({root:e.nativeRoot,file:i,maxBytes:Qj,label:`Native transition journal ${t}`});return aO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function yi(e,t){let i=await Sh(e,t);if(!i)return null;if(i.status==="migration-required")throw new zo(t);return i.journal}async function Wo(e){if(await tr(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await Co(e.paths,e.nextState.name);let t={schema:_i,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??Uj(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=Fl(t,t.change),n=Be(e.paths,i.change);if(await A(e.paths.nativeRoot,n),await yi(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await de(n,i),i}function jN(e,t){if(wi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(wi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function ON(e,t){if(wi(e,t.nextState))return"next";if(wi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function oO(e){let{journal:t}=e;return FN({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function FN(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function $N(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=oO({sequence:a.index+1,journal:t,type:a.event.type});if(!wi(FN(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function Ni(e,t,i){if(await tr(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Co(e,t);let n=await yi(e,t);if(!n)return null;let r=C(e,t),a=$N(await qe(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([ye(r),W(e,t)]),c=jN(o,n),l=ON(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await Zn(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!wi(await ye(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await Gr(e,n.nextState,n.previousState.revision);if(!wi(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!wi(await W(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await yi(e,t);if(!u||!wi(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=$N(await qe(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Hn({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let f=d.transitioned;f||(f=await Hn({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await lr({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([ye(r),W(e,t)]);jN(p,{...n,previousRun:n.nextRun}),ON(m,{...n,previousState:n.nextState});let h=await yi(e,t);if(!h||!wi(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await Kj.rm(Be(e,t),{force:!0}),n.nextState}async function LN(e,t,i){return re(e,`continue transition ${t}`,()=>He(e,t,`continue transition ${t}`,()=>Ni(e,t,i)))}import Rb from"node:path";import qN from"node:path";var sO="comet.native.acceptance.v1",cO=/^acceptance-[a-f0-9]{64}$/u,lO=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),uO=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,dO=/^[a-f0-9]{64}$/u,fO=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function hO(e,t){return e<t?-1:e>t?1:0}var Vi=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ko=Object.freeze({maxCriteria:1024}),Uo="<!-- comet-native:acceptance-evidence:start -->",da="<!-- comet-native:acceptance-evidence:end -->";function BN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",n=0;for(let r of e){let a=Buffer.byteLength(r,"utf8");if(n+a>t)break;i+=r,n+=a}return{value:i,truncated:!0}}function VN(e,t){let i=t.toString(36),n=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function pO(e){if(!dO.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=fO.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function mO(e,t){let i=BN(e.text,Vi.maxTextBytes),n=e.context.slice(0,Vi.maxContextItems).map(r=>BN(r,Vi.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:n.map(r=>r.value),text:i.value,contextTruncated:e.context.length>n.length||n.some(r=>r.truncated),textTruncated:i.truncated,verificationStatus:t}}function Ll(e){let t=pO({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(hO),r=n.slice(0,Vi.maxFailedCheckIds),a=e.criteria.slice(t,t+Vi.maxItems);for(let c of a){let l=[...i,mO(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:u<e.criteria.length?VN(e.acceptanceHash,u):null,limits:{...Vi}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Vi.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:o<e.criteria.length?VN(e.acceptanceHash,o):null,limits:{...Vi}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Vi.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Rh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function kh(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function JN(e){return e.includes("-->")||e.includes("--!>")}function*fa(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
190
+ ${$o(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function EI(e){if(Do(e)<=mi)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Sy("sha256");a.update(`${vI}
191
+ `),e.omissionOverflow&&An(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,An(a,"omission",f)},s=f=>{n+=1,r+=1,An(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let p=i[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(f,1),p}return null},l=()=>({...e,complete:n===0,entries:t,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Do(u)>mi;){if(i.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(i.length/4));for(let m=0;m<p;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:r}}}function nh(e){let t=Ti(e),i=t.entries.map((r,a)=>NI(r,`Snapshot entry ${a}`));if(i.sort(SI),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=t.omitted.map((r,a)=>bI(r,`Snapshot omission ${a}`));return n.sort(kI),EI({schema:ky,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:n,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function pl(e){let t=new Map;for(let[i,n]of e.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:xn(n.path,`Declared artifact ${i} path`),kind:n.kind},a=t.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);t.set(r.path,r)}return[...t.values()].sort((i,n)=>Ge(i.path,n.path)||Ge(i.kind,n.kind))}function ml(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function gy(e){return e?{hash:e.hash,size:e.size}:null}function Cy(e,t,i){let n=0,r=0;for(;n<e.entries.length||r<t.entries.length;){let a=e.entries[n],o=t.entries[r],s=a===void 0?1:o===void 0?-1:Ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(n+=1),s>=0&&(r+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:gy(c),after:gy(l)})}}function RI(e,t){return{...e,attributedTo:t.filter(i=>ml(i,e.path))}}function Hi(e,t){return{id:`scope:${H(pI,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function CI(e,t){let i=t.omitted.map(n=>Hi({kind:"snapshot-omission",source:e,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${e} snapshot omitted ${n.path}: ${n.reason}`));return t.complete||i.push(Hi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Hi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function wy(e,t){return CI(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function rh(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||yI(e.path,t.path)||Ge(e.id,t.id)}function PI(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(rh)}function AI(e){return[...new Set(e.map((t,i)=>xn(t,`Git path ${i}`)))].sort(Ge)}function Py(e){if(typeof e.contractHash!="string"||!ah.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:pl(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:AI(e.gitChangedPaths)}}}function xI(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Cy(e,t,d=>{let f=i.some(p=>ml(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<gI){let p=RI(d,i),m=Do(p);s+m<=mi?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function Ay(e,t){return Hi({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function TI(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:Zr(Number(t[1]),"Scope overflow change count"),unresolved:Zr(Number(t[2]),"Scope overflow unresolved count"),unattributed:Zr(Number(t[3]),"Scope overflow unattributed count")},n=nr(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Ay(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function _I(e){let t=Sy("sha256");t.update(`${mI}
192
+ `);let i=0;Cy(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){An(t,"change",r);let a=0;for(let o of e.declaredArtifacts)ml(o,r.path)&&(a+=1,An(t,"change-attribution",o));An(t,"change-end",{attributionCount:a}),a===0&&An(t,"unattributed-change",{after:r.after,before:r.before,changeKind:r.kind,path:r.path})}i+=1});let n=0;for(let[r,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)n>=e.detailedOmissionCount&&An(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function xy(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=xI(e,t,r,i.gitChangedPaths),s=H(Ho,e),c=H(Ho,t),l=[];for(let[w,y]of[["baseline",e],["current",t]])for(let g of y.omitted){if(l.length>=wI)break;l.push(Hi({kind:"snapshot-omission",source:w,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${w} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...wy("baseline",e),...wy("current",t),...o.totalChanges===0&&a===null?[Hi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(i.gitChangedPaths===void 0)return;let w=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(y=>w.has(y)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(y=>!w.has(y))}},p=w=>{let y=o.candidates.slice(0,w.detailedChangeCount),g=y.filter(ii=>ii.attributedTo.length===0),k=o.totalChanges-y.length,x=o.totalUnattributed-g.length,U=u-w.detailedOmissionCount,D=x+U,z=[...g.map(ii=>Hi({kind:"unattributed-change",source:"implementation-scope",path:ii.path,evidence:{after:ii.after,before:ii.before,changeKind:ii.kind}},`Changed path is not covered by a declared artifact: ${ii.path}`)),...l.slice(0,w.detailedOmissionCount),...d,...k>0||D>0?[Ay(w.overflowHash,{changes:k,unattributed:x,unresolved:D})]:[]],ne=PI(z),ti=w.includeGitAdvisory?f():void 0;return{schema:th,contractHash:n,baselineProjectionRef:ih(s),baselineProjectionHash:s,currentProjectionRef:ih(c),currentProjectionHash:c,complete:ne.length===0,declaredArtifacts:r,changes:y,unattributed:g,unresolvedScopes:ne,noCodeReason:a,...ti?{gitAdvisory:ti}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,b="0".repeat(64);for(;;){let w=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:b});if(Do({...w,scopeHash:b})<=mi)break;if(v){v=!1;continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>m||u>h?_I({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):b,S=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N}),R={...S,scopeHash:H(Ey,S)};if(Do(R)>mi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function Tn(e){let t=nh(e.baseline),i=nh(e.current),n=Py(e);return{authority:n,baseline:t,current:i,scope:xy(t,i,n)}}var II=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Di(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mi(e,t,i,n){let r=new Set([...t,...i]),a=Object.keys(e).filter(s=>!r.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${n} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${n} is missing field(s): ${o.join(", ")}`)}function nr(e,t){if(typeof e!="string"||!ah.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yy(e,t,i){let n=ih(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function ea(e,t){let i=Di(e,"Native snapshot projection");if(Mi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==ky)throw new Error("Native snapshot projection schema is invalid");let n=Ti({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),r=nh(n);if(H(Ho,i)!==H(Ho,r))throw new Error("Native snapshot projection is not canonical");let a=H(Ho,r);if(t!==void 0&&nr(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function oh(e,t){let i=Di(e,`Declared artifact ${t}`);if(Mi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:xn(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Ny(e,t){if(e===null)return null;let i=Di(e,t);return Mi(i,["hash","size"],[],t),{hash:nr(i.hash,`${t} hash`),size:Zr(i.size,`${t} size`)}}function by(e,t){let i=Di(e,`Implementation change ${t}`);if(Mi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let n=i.attributedTo.map(oh),r=pl(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Ny(i.before,`Implementation change ${t} before`),o=Ny(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:xn(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function jI(e,t){let i=Di(e,`Unresolved scope ${t}`);Mi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let n=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!n.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Ry(i.path,`Unresolved scope ${t} path`):xn(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function hl(e,t){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((r,a)=>xn(r,`${t} ${a}`)),n=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function ta(e){let t=Di(e,"Native implementation scope"),i=[...II].filter(y=>y!=="gitAdvisory");if(Mi(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==th)throw new Error("Native implementation scope schema is invalid");let n=nr(t.contractHash,"Implementation scope contractHash"),r=nr(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=yy(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=nr(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=yy(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(oh);if(JSON.stringify(c)!==JSON.stringify(pl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(by),u=[...l].sort((y,g)=>Ge(y.path,g.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(g=>ml(g,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(by),p=l.filter(y=>y.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(jI),h=m.filter(y=>y.kind==="scope-detail-overflow");if(h.length>1)throw new Error("Implementation scope has multiple detail overflow records");let v=h[0]===void 0?null:TI(h[0]);if(v&&(v.changes+v.unresolved===0||v.unattributed>v.changes||v.unattributed>v.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let b=t.noCodeReason,E=[...p.map(y=>Hi({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(v?.changes??0)===0&&b===null?[Hi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:r,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],N=m.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(rh))||new Set(m.map(y=>y.id)).size!==m.length||JSON.stringify(N)!==JSON.stringify(E.sort(rh))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let y=Di(t.gitAdvisory,"Implementation scope Git advisory");if(Mi(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=hl(y.changedPaths,"Git changed paths"),k=hl(y.pathsPresentInSnapshotChanges,"Git present paths"),x=hl(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),U=[...k,...x].sort(Ge),D=new Set(l.map(z=>z.path));if(JSON.stringify(U)!==JSON.stringify(g)||(v?.changes??0)===0&&k.some(z=>!D.has(z))||x.some(z=>D.has(z)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:k,pathsAbsentFromSnapshotChanges:x}}let R={schema:th,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:b,...S?{gitAdvisory:S}:{}},w=nr(t.scopeHash,"Implementation scope scopeHash");if(H(Ey,R)!==w)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:w}}function OI(e){let t=Di(e,"Native implementation scope authority");if(Mi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(oh);if(JSON.stringify(i)!==JSON.stringify(pl(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;t.gitChangedPaths!==void 0&&(n=hl(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Py({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Wt(e){let t=Di(e,"Native implementation scope bundle");Mi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=OI(t.authority),n=ea(t.baseline),r=ea(t.current),a=ta(t.scope),o=xy(n,r,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:n,current:r,scope:o}}function Ty(e){let t=ta(e.scope);return Wt({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{}},baseline:e.baseline,current:e.current,scope:t})}import _y from"node:path";var $I=/\b(Bearer|Basic)\s+[^\s"']+/giu,HI=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,DI=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,MI=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,FI=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,LI=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,qI=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Ne(e){return e.replace($I,"$1 [REDACTED]").replace(HI,"[REDACTED PRIVATE KEY]").replace(DI,"$1[REDACTED]@").replace(MI,"[REDACTED TOKEN]").replace(FI,'$1"[REDACTED]"').replace(LI,"$1$2$1$3$4[REDACTED]$4").replace(qI,"$1$2[REDACTED]")}var Iy=/^[a-f0-9]{64}$/u,BI=8,jy="comet.native.acceptance-trace.v2",Oy="comet.native.partial-allowance.v1",$y="comet.native.verification-evidence.v2";function It(e,t){if(!Iy.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function yl(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Nl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function ia(e,t,i=2e3){let n=Ne(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function _n(e,t){let i=_y.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||_y.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function Hy(e,t,i){let n=_n(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=ai(n),a=n.toLowerCase(),o=i?_n(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Mo(e){let t=_n(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Dy(e){let t=e.toISOString();if(Number.isNaN(Date.parse(t)))throw new Error("Native evidence timestamp is invalid");return t}function VI(e){return H("comet.native.acceptance-set.v1",[...e].sort((t,i)=>jt(t.id,i.id)))}function jt(e,t){return e<t?-1:e>t?1:0}function My(e,t,i){let n=_n(i.nativeRootRef,"Native root ref"),r=new Map(e.map(u=>[u.id,u]));if(r.size!==e.length)throw new Error("Native contract has duplicate acceptance IDs");let a=new Map;for(let u of t){if(!r.has(u.acceptance_id))throw new Error(`Verification references unknown acceptance ID: ${u.acceptance_id}`);if(a.has(u.acceptance_id))throw new Error(`Verification repeats acceptance ID: ${u.acceptance_id}`);a.set(u.acceptance_id,u)}let o=[...r.keys()].filter(u=>!a.has(u));if(o.length>0&&i.allowMissing!==!0){let u=o.slice(0,BI),d=o.length-u.length;throw new Error(`Verification is missing ${o.length} acceptance evidence entr${o.length===1?"y":"ies"}: ${u.join(", ")}${d>0?`, ... (${d} more)`:""}`)}let s=[...r.values()].sort((u,d)=>jt(u.id,d.id)).map(u=>{let d=a.get(u.id);if(!d)return{acceptanceId:u.id,status:"missing",kind:u.kind,source:_n(u.source,`Acceptance source for ${u.id}`),evidenceRefs:[],skippedReason:null};let f=d.status,p=[...d.evidence_refs].map(v=>Mo(v)).sort();if(new Set(p).size!==p.length)throw new Error(`Verification repeats an evidence ref for ${u.id}`);let m=d.skipped_reason?.trim()||null,h=m===null?null:ia(m,`Skipped reason for ${u.id}`);if(f==="passed"&&(p.length===0||h!==null)||f==="failed"&&p.length===0&&h===null)throw new Error(`Acceptance ${u.id} has an invalid evidence state`);return{acceptanceId:u.id,status:f,kind:u.kind,source:_n(u.source,`Acceptance source for ${u.id}`),evidenceRefs:p,skippedReason:h}}),c=VI(e),l={schema:"comet.native.acceptance-trace.v2",nativeRootRef:n,criteriaHash:c,total:s.length,evidenced:s.filter(u=>u.evidenceRefs.length>0).length,skipped:s.filter(u=>u.skippedReason!==null).length,entries:s};return{...l,traceHash:H(jy,l)}}function Fy(e){let t=Wt(e.scopeBundle).scope;if(t.complete)throw new Error("Complete implementation scope cannot be partially allowed");let i=new Set(t.unresolvedScopes.map(s=>s.id));if(new Set(e.allowedScopeIds).size!==e.allowedScopeIds.length)throw new Error("Partial allowance has duplicate allowed scope IDs");let n=[...e.allowedScopeIds].sort(jt);if(n.length===0)throw new Error("Partial allowance requires at least one scope ID");if([...i,...n].some(s=>!/^scope:[a-f0-9]{64}$/u.test(s)))throw new Error("Partial allowance scope IDs are invalid");let r=n.filter(s=>!i.has(s)),a=[...i].filter(s=>!n.includes(s));if(r.length>0)throw new Error(`Partial allowance has unknown scope IDs: ${r}`);if(a.length>0)throw new Error(`Partial allowance is missing scope IDs: ${a}`);let o={schema:"comet.native.partial-allowance.v1",change:Nl(e.change),scopeHash:t.scopeHash,scopeIds:n,reason:ia(e.reason,"Partial allowance reason"),confirmedSummary:ia(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:yl(e.sourceRevision),confirmedAt:Dy(e.now??new Date)};return{...o,allowanceHash:H(Oy,o)}}function Ly(e){if(e.result!=="pass"&&e.result!=="fail")throw new Error("Native verification evidence result is invalid");let t=By(e.acceptanceTrace),i=Wt(e.implementationScope.bundle).scope,n=wl(e.implementationScope.ref,"scopes",i.scopeHash);if(i.contractHash!==e.contractHash)throw new Error("Implementation scope does not match the verification contract");let r=e.partialAllowance??null,a=r?Fo(r.allowance):null,o=r&&a?{ref:wl(r.ref,"allowances",a.allowanceHash),allowance:a}:null;if(i.complete&&o!==null)throw new Error("Complete implementation scope must not use a partial allowance");if(!i.complete&&o===null)throw new Error("Partial implementation scope requires a confirmed allowance");let s=i.unresolvedScopes.map(f=>f.id).sort(jt);if(o&&(o.allowance.change!==e.change||o.allowance.scopeHash!==i.scopeHash||JSON.stringify(o.allowance.scopeIds)!==JSON.stringify(s)))throw new Error("Partial allowance does not match the verification scope");if(t.criteriaHash!==e.acceptanceHash)throw new Error("Acceptance trace does not match the verification contract");if(o&&o.allowance.sourceRevision>=e.sourceRevision)throw new Error("Partial allowance must precede the verification evidence revision");let c=[...new Set(t.entries.flatMap(f=>f.evidenceRefs))].sort(jt),l=[...new Set(e.requiredReceiptRefs.map(Mo))].sort(jt),u=c;if(e.result==="pass"&&l.length===0)throw new Error("Passing verification requires at least one current required check receipt");let d={schema:"comet.native.verification-evidence.v2",change:Nl(e.change),sourceRevision:yl(e.sourceRevision),result:e.result,freshness:i.complete?"complete":"partial",contractHash:It(e.contractHash,"Verification contractHash"),acceptanceCriteriaHash:It(e.acceptanceHash,"Verification acceptanceHash"),implementationScopeRef:n,implementationScopeHash:i.scopeHash,reportRef:Hy(e.reportRef,"Verification report ref"),reportHash:It(e.reportHash,"Verification report hash"),acceptanceTrace:t,partialAllowanceRef:o?.ref??null,partialAllowanceHash:o?.allowance.allowanceHash??null,requiredReceiptRefs:l,receiptRefs:u,createdAt:Dy(e.now??new Date)};return{...d,envelopeHash:H($y,d)}}function vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gl(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function qy(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function wl(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let n=`runtime/evidence/${t}/${i}.json`;if(e!==n)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function By(e){let t=vl(e,"Native acceptance trace");if(gl(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Iy.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=_n(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=vl(o,`Native acceptance trace entry ${s}`);if(gl(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>Mo(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(jt))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:_n(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:ia(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>jt(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||t.total!==n.length||t.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==n.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let r={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:n},a=It(t.traceHash,"Native acceptance trace hash");if(H(jy,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function Fo(e){let t=vl(e,"Native partial allowance");if(gl(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(jt))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Nl(t.change),scopeHash:It(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:ia(t.reason,"Partial allowance reason"),confirmedSummary:ia(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:yl(t.sourceRevision),confirmedAt:qy(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=It(t.allowanceHash,"Native partial allowance hash");if(H(Oy,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function na(e){let t=vl(e,"Native verification evidence");if(gl(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=It(t.implementationScopeHash,"Native verification implementation scope hash"),n=By(t.acceptanceTrace),r=It(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(n.criteriaHash!==r)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:It(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Mo(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(jt)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(jt);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>Mo(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(jt)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Nl(t.change),sourceRevision:yl(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:It(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:wl(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:Hy(t.reportRef,"Native verification report ref"),reportHash:It(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:wl(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:qy(t.createdAt,"Native verification timestamp")},d=It(t.envelopeHash,"Native verification envelope hash");if(H($y,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Vy from"node:path";var bl="comet.native.check-receipt.v1",Wy="comet.native.check-receipt.v1",In="scoped-text-safety",Lo=1,Pe=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),JI=/^[a-f0-9]{64}$/u,zI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WI="comet.native.checker-policy.v1",UI="comet.native.check-input.v1",KI=2048,Sl=H(WI,{policy:In,version:Lo,limits:Pe,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),GI=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Jy=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Uy=["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"],YI=new Set(Uy);function ar(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function or(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Fi(e,t){if(typeof e!="string"||!JI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function rr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Ky(e,t){let i=rr(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function zy(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function XI(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>KI||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Vy.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Vy.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function QI(e){let t=ar(e,"Native check receipt checker");or(t,["policy","version","hash","limits"],"Native check receipt checker");let i=ar(t.limits,"Native check receipt limits");if(or(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==In||t.version!==Lo||t.hash!==Sl||i.maxFiles!==Pe.maxFiles||i.maxFileBytes!==Pe.maxFileBytes||i.maxTotalBytes!==Pe.maxTotalBytes||i.maxIssues!==Pe.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:In,version:Lo,hash:Sl,limits:{...Pe}}}function ZI(e){let t=ar(e,"Native check receipt contract");return or(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Fi(t.expectedHash,"Native check expected contract hash"),beforeHash:Fi(t.beforeHash,"Native check before contract hash"),afterHash:Fi(t.afterHash,"Native check after contract hash")}}function ej(e){let t=ar(e,"Native check receipt implementation");return or(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Fi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Fi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Fi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Fi(t.afterSnapshotHash,"Native check after snapshot hash")}}function tj(e){let t=ar(e,"Native check receipt counts");or(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:rr(t.filesSelected,"Native check filesSelected"),filesScanned:rr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:rr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:rr(t.bytesScanned,"Native check bytesScanned"),issueCount:rr(t.issueCount,"Native check issueCount"),recordedIssueCount:rr(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>Pe.maxFiles||i.bytesScanned>Pe.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>Pe.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function ij(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Jy.indexOf(e.kind)-Jy.indexOf(t.kind)}function nj(e){if(!Array.isArray(e)||e.length>Pe.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=ar(n,`Native check issue ${r}`);if(or(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!GI.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:XI(a.path,`Native check issue ${r} path`),line:Ky(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(ij);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function rj(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!YI.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Uy.filter(n=>t.includes(n));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function Gy(e){return H(UI,e)}function Li(e){let t=ar(e,"Native check receipt");if(or(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==bl)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!zI.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Ky(t.sourceRevision,"Native check source revision"),n=QI(t.checker),r=ZI(t.contract),a=ej(t.implementation),o=Gy({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Fi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=zy(t.startedAt,"Native check receipt startedAt"),c=zy(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=tj(t.counts),u=nj(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=rj(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.filesSelected>Pe.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>Pe.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:bl,change:t.change,sourceRevision:i,checker:n,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:r,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},m=Fi(t.receiptHash,"Native check receipt content hash");if(H(Wy,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}function Yy(e){let t={policy:In,version:Lo,hash:Sl,limits:{...Pe}},i={schema:bl,...e,checker:t,inputHash:Gy({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return Li({...i,receiptHash:H(Wy,i)})}var kl="comet.native.verification-receipt.v3",Xy=kl,aj="comet.native.declared-artifacts.v1",oj=/^[a-f0-9]{64}$/u,sj=/^acceptance-[a-f0-9]{64}$/u,cj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,uj=4096,dj=256,fj=1024;function ra(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function jn(e,t,i){let n=Object.keys(e).sort(),r=[...t].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function qi(e,t){if(typeof e!="string"||!oj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ut(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=Ne(e).trim();if(!i||i.length>uj||i!==e.trim())throw new Error(`${t} is invalid`);return i}function sh(e,t){let i=Ut(e,t),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function qo(e,t,i=Ut,n=!1,r=dj){if(!Array.isArray(e)||e.length>r||!n&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function hj(e,t){if(typeof e!="string"||!sj.test(e))throw new Error(`${t} is invalid`);return e}function pj(e){let t=ra(e,"Native verification receipt bindings");if(jn(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!cj.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:qi(t.contractHash,"Native verification receipt contract hash"),scopeHash:qi(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:qi(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:qi(t.artifactHash,"Native verification receipt artifact hash")}}function mj(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=lj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function vj(e,t,i,n){let r=ra(t,`Native ${e} evidence`);if(e==="automated-check"){if(jn(r,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(r.exitCode)||!Number.isSafeInteger(r.timeoutMs)||r.timeoutMs<1||r.timeoutMs>3600*1e3||typeof r.timedOut!="boolean"||typeof r.outputTruncated!="boolean"||r.signal!==null&&typeof r.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=sh(r.startedAt,"Native automated-check start time"),o=sh(r.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&r.exitCode!==0||i==="failed"&&r.exitCode===0||i==="passed"&&(r.timedOut||r.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ra(r.worktree,"Native automated-check worktree");if(jn(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=ra(r.afterFence,"Native automated-check after fence");if(jn(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ut(r.executable,"Native automated-check executable"),args:qo(r.args,"Native automated-check arguments",Ut,!0),cwd:Ut(r.cwd,"Native automated-check cwd"),exitCode:r.exitCode,signal:r.signal,timedOut:r.timedOut,timeoutMs:r.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ut(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:qi(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:qi(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:qi(r.outputHash,"Native automated-check output hash"),outputSummary:Ut(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){jn(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=mj(r.checkReceiptRef);if(qi(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:qo(r.subjects,"Native static inspection subjects",Ut,n==="required-check"),rule:Ut(r.rule,"Native static inspection rule"),resultSummary:Ut(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return jn(r,["steps","observations"],"Native manual-evidence evidence"),{steps:qo(r.steps,"Native manual evidence steps"),observations:qo(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Qy(e){let t=ra(e,"Native verification receipt");if(jn(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,n=t.role,r=t.status,a=Ut(t.actor,"Native verification receipt actor"),o=qo(t.acceptanceIds,"Native receipt acceptance IDs",hj,n==="required-check",fj).sort();if(n==="required-check"&&o.length!==0||n==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(n==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:kl,kind:i,role:n,status:r,bindings:pj(t.bindings),acceptanceIds:o,actor:a,issuedAt:sh(t.issuedAt,"Native verification receipt issue time"),evidence:vj(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==In||s.actor!==`native-runtime:${In}`))throw new Error("Native required check policy identity is invalid");return s}function El(e){let t=Qy({schema:kl,...e});return{...t,receiptHash:H(Xy,t)}}function Bo(e){let t=ra(e,"Native verification receipt");if(jn(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==kl)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=Qy(n),a=qi(t.receiptHash,"Native verification receipt hash");if(H(Xy,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function Rl(e){return H(aj,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}function Zy(e){return e.kind==="static-inspection"?`static:${e.evidence.rule}`:e.kind==="automated-check"?`automated:${H("comet.native.failed-check.v1",{executable:e.evidence.executable,args:e.evidence.args,acceptanceIds:e.acceptanceIds})}`:`manual:${H("comet.native.failed-check.v1",{acceptanceIds:e.acceptanceIds})}`}var rN=/^[a-f0-9]{64}$/u,Gt=mi,yB=3*Gt;function ch(e,t){let i=vi.relative(e,t);return i===""||!vi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vi.sep}`)}function gj(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function eN(e){let t=await Kt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Kt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function wj(e,t){let i=vi.resolve(e),n=vi.resolve(t);if(!ch(i,n))throw new Error("Native evidence path is outside its change");let r=[await eN(i)],a=i;for(let o of vi.relative(i,n).split(vi.sep).filter(Boolean)){a=vi.join(a,o);let s=await eN(a);if(!ch(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function tN(e){for(let t of e){let i=await Kt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!gj(t,i)||await Kt.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function yj(e,t,i={}){let n=await wj(t,vi.dirname(e));await i.afterParentChainCaptured?.();let r=await Kt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Kt.realpath(e);if(!ch(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Kt.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Kt.lstat(e),Kt.realpath(e)]);if(await tN(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Cl(s,r)||!Cl(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Gt)throw new Error(`Native evidence document exceeds ${Gt} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Gt+1-d,b=await o.read(f,0,Math.min(f.length,v),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>Gt)throw new Error(`Native evidence document exceeds ${Gt} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Kt.lstat(e),Kt.realpath(e)]);if(await tN(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Cl(s,p)||!Cl(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function wt(e,t){if(!rN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function aN(e){return wt("reports",e)}async function oN(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Gt||nN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return sr({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Nj(e,t,i,n,r){if(!rN.test(i))throw new Error("Native report evidence hash is invalid");let a=await Bi({paths:e,name:t,kind:"reports",hash:i,hooks:n,changeDir:r});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||nN("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function aa(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function sN(e,t,i,n,r){return vi.join(r??C(e,t),...wt(i,n).split("/"))}async function Bi(e){let t=e.changeDir??C(e.paths,e.name),i=sN(e.paths,e.name,e.kind,e.hash,t);return await A(e.paths.nativeRoot,i),yj(i,t,e.hooks)}async function sr(e){Pl(e.value);let t=sN(e.paths,e.name,e.kind,e.hash);await A(e.paths.nativeRoot,t);try{let n=await Bi(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return wt(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await de(t,e.value,{containedRoot:e.paths.nativeRoot});let i=await Bi(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return wt(e.kind,e.hash)}function Pl(e){if(bj(e)>Gt)throw new Error(`Native evidence document exceeds ${Gt} bytes`)}function bj(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
193
+ `,"utf8")}function iN(e,t){return ea(e,t)}function Sj(e,t){let i=ta(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function cN(e,t,i){let n=Fo(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function lN(e,t,i){let n=na(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function uN(e,t,i,n=!1,r){let a=await Al(e,t,i.implementationScopeRef,void 0,r);if(n&&await Nj(e,t,i.reportHash,void 0,r),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await lh(e,t,i.partialAllowanceRef,void 0,r);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function dN(e){let t=Wt(e.bundle),{baseline:i,current:n,scope:r}=t;return Pl(i),Pl(n),Pl(r),await sr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.baselineProjectionHash,value:i}),await sr({paths:e.paths,name:e.name,kind:"snapshots",hash:r.currentProjectionHash,value:n}),sr({paths:e.paths,name:e.name,kind:"scopes",hash:r.scopeHash,value:r})}async function gi(e,t,i,n,r){let a=aa(i,"scopes"),o=Sj(await Bi({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=aa(o.baselineProjectionRef,"snapshots"),c=aa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Bi({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>iN(d,s)),Bi({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>iN(d,c))]);return Ty({baseline:l,current:u,scope:o})}async function Al(e,t,i,n,r){return(await gi(e,t,i,n,r)).scope}async function fN(e){let t=cN(e.allowance,e.name,e.allowance.allowanceHash),i=await Al(e.paths,e.name,wt("scopes",t.scopeHash)),n=i.unresolvedScopes.map(r=>r.id).sort();if(i.complete||JSON.stringify(n)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return sr({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function lh(e,t,i,n,r){let a=aa(i,"allowances");return cN(await Bi({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function xl(e){let t=Bo(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return sr({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function oa(e,t,i,n,r){let a=aa(i,"receipts"),o=Bo(await Bi({paths:e,name:t,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function hN(e){let t=lN(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await uN(e.paths,e.name,t,!0),sr({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function On(e,t,i,n,r){let a=aa(i,"verifications"),o=lN(await Bi({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await uN(e,t,o,!1,r),o}async function kj(e){try{let t=await pt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:st.maxChanges});return await t.verify(),t.entries}catch(t){if(t.code==="ENOENT")return[];throw t}}async function Ej(e,t){let i=await W(e,t),[n,r]=await Promise.all([i.implementation_scope?Al(e,t,i.implementation_scope):null,ul(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:n?.declaredArtifacts??[],workspaceIdentityHash:r?.nativeRootId??null}}async function Rj(e){let i=(await kj(e)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();return Promise.all(i.map(n=>Ej(e,n)))}async function Tl(e,t){let i=await Rj(e);eh(i);let n=i.find(o=>o.name===t);if(!n)throw new Error(`Native conflict target is not visible: ${t}`);let r=0,a=0;for(let o of i){if(o.name===t)continue;let s=eh([n,o]).relationships[0];s.classification==="definite-conflict"&&(r+=1),s.classification==="possible-overlap"&&(a+=1)}return{definiteConflictCount:r,possibleOverlapCount:a,findingCodes:[...r>0?["native-change-conflict"]:[],...a>0?["native-change-overlap"]:[]]}}import{randomUUID as Kj}from"crypto";import{promises as Gj}from"fs";import Yj from"path";import{isDeepStrictEqual as vh}from"util";var Cj="comet.native.repair-signature.v1",yt={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3},Pj="comet.native.repair-signature.v1",Aj="comet.native.repair-override-summary.v1",xj=/^[a-f0-9]{64}$/u,Tj=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function mN(e,t){return e<t?-1:e>t?1:0}function _l(e,t){if(typeof e!="string"||!xj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function uh(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Il(e,t,i,n){if(!Array.isArray(e)||e.length>i||!n&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let r=e.map(a=>{if(typeof a!="string"||!Tj.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(mN)}function sa(e=[]){return Il(e,"Native repair failed check IDs",yt.maxFailedCheckIds,!0)}function vN(e){let t=sa(e.failedCheckIds),i=Il(e.failedAcceptanceIds,"Native repair failed acceptance IDs",yt.maxFailedAcceptanceIds,!0),n={schema:Cj,contractHash:_l(e.contractHash,"Native repair contract hash"),failedAcceptanceIds:i,failedCheckIds:t};return{...n,signatureHash:H(Pj,n)}}function _j(e){if(!Array.isArray(e)||e.length>yt.maxHistoryRecords)throw new Error("Native repair history exceeds its record boundary");let t=0,i=0;return e.map((n,r)=>{if(!n||n.kind!=="failure"&&n.kind!=="override")throw new Error(`Native repair history record ${r} is invalid`);let a=n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?["iteration","kind","revision","signatureHash"]:["failedAcceptanceIds","failedCheckIds","iteration","kind","revision","signatureHash"]:["iteration","kind","revision","signatureHash","summaryHash"],o=Object.keys(n).sort(mN);if(o.length!==a.length||o.some((f,p)=>f!==a[p]))throw new Error(`Native repair history record ${r} fields are invalid`);let s=uh(n.iteration,`Native repair history ${r} iteration`),c=uh(n.revision,`Native repair history ${r} revision`),l=r>0?e[r-1]:null;if(!(n.kind==="override"&&l?.kind==="failure"&&s===t&&c>=i&&n.signatureHash===l.signatureHash)&&(s<=t||c<=i))throw new Error("Native repair history must be strictly ordered by revision and iteration");t=s,i=c;let d=_l(n.signatureHash,`Native repair history ${r} signature`);return n.kind==="failure"?n.failedAcceptanceIds===void 0&&n.failedCheckIds===void 0?{kind:"failure",iteration:s,revision:c,signatureHash:d}:{kind:"failure",iteration:s,revision:c,signatureHash:d,failedAcceptanceIds:Il(n.failedAcceptanceIds??[],`Native repair history ${r} failed acceptance IDs`,yt.maxFailedAcceptanceIds,!0),failedCheckIds:Il(n.failedCheckIds??[],`Native repair history ${r} failed check IDs`,yt.maxFailedCheckIds,!0)}:{kind:"override",iteration:s,revision:c,signatureHash:d,summaryHash:_l(n.summaryHash,`Native repair history ${r} summary`)}})}function pN(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function Ij(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:pN(e.failedAcceptanceIds,t.failedAcceptanceIds)&&pN(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Vo(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(Ij(n,a))break;i+=1,n=a}return i}function gN(e){let t=e.trim();if(t.length===0||t.length>yt.maxOverrideSummaryCharacters)throw new Error("Native repair override summary is invalid");return t}function jl(e){return H(Aj,{summary:gN(e)})}function wN(e){let t=vN(e.facts),i=_j(e.history),n=i.filter(l=>l.kind==="failure"),r=n.length+1,a=uh(e.maxVerifyFailures,"Native maximum Verify failures"),o=Math.max(0,a-r),s=Vo({signatureHash:t.signatureHash,failedAcceptanceIds:t.failedAcceptanceIds,failedCheckIds:t.failedCheckIds},n);if(r>=a)return{disposition:"hard-stop",reasonCode:"repair-iteration-limit",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(s<yt.warningAtConsecutiveFailures)return{disposition:"continue",reasonCode:"new-failure-signature",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(s<yt.manualStopAtConsecutiveFailures)return{disposition:"warn",reasonCode:"repeated-failure-warning",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1};if(e.override){if(_l(e.override.expectedSignatureHash,"Native repair override expected signature")!==t.signatureHash)throw new Error("Native repair override does not match the current failure signature");gN(e.override.summary);let u=i.some(d=>d.kind==="override"&&d.signatureHash===t.signatureHash);return{disposition:u?"manual-stop":"continue",reasonCode:u?"override-already-used":"override-accepted",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!u}}return{disposition:"manual-stop",reasonCode:i.some(l=>l.kind==="override"&&l.signatureHash===t.signatureHash)?"override-already-used":"repeated-failure-stop",signature:t,consecutiveFailures:s,totalRepairFailures:r,remainingIterations:o,overrideAccepted:!1}}function $n(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var yN="repairStagnation",Nt={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},Oj=/^[a-f0-9]{64}$/u,NN="comet.native.repair-scope.v1",$j=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),Hj=["data","runId","sequence","timestamp","type"],bN=["disposition","overrideSummaryHash","signatureHash"],Dj=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],SN=12;function Ol(e,t){return e<t?-1:e>t?1:0}function fh(e,t,i){let n=Object.keys(e).sort(Ol);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function Jo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function ca(e,t){if(typeof e!="string"||!Oj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Mj(e){if(!Array.isArray(e)||e.length>yt.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Ol)}function la(e){let t=Wt(e).scope;return H(NN,{schema:NN,contractHash:t.contractHash,artifactSnapshotHash:t.currentProjectionHash})}function kN(e){if(typeof e!="string"||e.length===0||e.length>Nt.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function dh(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Nt.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Nt.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${n} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Nt.maxTextCharacters&&(!r||e.length>Nt.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${n} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${n} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Nt.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>dh(s,t+1,i,`${n}[${c}]`));return}let a=Jo(e,n),o=Object.keys(a);if(o.length>Nt.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Nt.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Nt.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");dh(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function Fj(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function Lj(e,t,i){let n=Jo(e,`Native repair trajectory event ${t+1}`);if(fh(n,Hj,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(Fj(n.timestamp),typeof n.type!="string"||!$j.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(kN(n.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let r={nodes:0,characters:0,ancestors:new Set};return dh(n.data,0,r,"Native trajectory event data"),Jo(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function hh(e){let t=Jo(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Ol),n=i.length===bN.length&&i.every((l,u)=>l===bN[u]);n||fh(t,Dj,"Native repair trajectory projection");let r=ca(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:ca(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=ca(t.contractHash,"Native repair trajectory contract hash"),s=Mj(t.failedAcceptanceIds),c=sa(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function qj(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function Bj(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??SN;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Vo({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<yt.warningAtConsecutiveFailures?"continue":a<yt.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function Vj(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??SN;if(n.length>=r)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||n.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function $l(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Nt.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=kN(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],n=null,r=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=Lj(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Nt.maxTotalDataNodes||c>Nt.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?ca(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?ca(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,yN)){if(n?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&r!==null&&p!==r||p===null&&(n?.disposition==="manual-stop"||n?.disposition==="hard-stop"))){i.length=0,n=null,r=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let m=hh(f[yN]);if(qj(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(i.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&p!==null&&r!==null&&p!==r&&(i.length=0,o=0),p!==null&&(r=p),Bj(m,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(n?.contractHash===null&&p!==null&&r!==null&&p!==r)throw new Error("Native repair override cannot cross implementation scope progress");Vj(m,i,n);let h=i.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(n=m,i.length>yt.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function EN(e){return $l(e).history}function RN(e){let t=$l(e).latestProjection;return t?{...t}:null}function CN(e){let t=$l(e),i=Jo(e.override,"Native repair override request");fh(i,["expectedSignatureHash","summary"],"Native repair override request");let n=ca(i.expectedSignatureHash,"Native repair override expected signature");if(typeof i.summary!="string")throw new Error("Native repair override summary is invalid");if(t.latestProjection?.disposition==="hard-stop")throw new Error("Native repair hard stop cannot be overridden");if(t.latestProjection?.disposition!=="manual-stop"||t.latestProjection.signatureHash!==n)throw new Error("Native repair override does not match the latest manual stop");if(t.history.some(a=>a.kind==="override"&&a.signatureHash===n))throw new Error("Native repair signature was already overridden");let r=jl(i.summary);return{history:t.history,eventProjection:{signatureHash:n,disposition:"continue",overrideSummaryHash:r,contractHash:t.latestProjection.contractHash,failedAcceptanceIds:[...t.latestProjection.failedAcceptanceIds],failedCheckIds:[...t.latestProjection.failedCheckIds],maxVerifyFailures:t.latestProjection.maxVerifyFailures}}}function Jj(e){let t=na(e.envelope),i=Wt(e.implementationScope);if(t.result!=="fail")throw new Error("Native repair stagnation requires a failed verification envelope");if(t.contractHash!==i.scope.contractHash||t.implementationScopeHash!==i.scope.scopeHash)throw new Error("Native repair evidence does not match the implementation scope authority");return{contractHash:i.scope.contractHash,implementationScopeHash:la(i),artifactSnapshotHash:i.scope.currentProjectionHash,failedAcceptanceIds:t.acceptanceTrace.entries.filter(n=>n.status==="failed"||n.status==="missing").map(n=>n.acceptanceId).sort(Ol),failedCheckIds:sa(e.failedCheckIds)}}function zj(e,t){return{signatureHash:e.signature.signatureHash,disposition:e.disposition,overrideSummaryHash:t,contractHash:e.signature.contractHash,failedAcceptanceIds:[...e.signature.failedAcceptanceIds],failedCheckIds:[...e.signature.failedCheckIds],maxVerifyFailures:e.totalRepairFailures+e.remainingIterations}}function Wj(e){let t=Jj(e),i=$l(e);return{facts:t,history:i.latestProjection?.contractHash!==null&&i.latestProjection?.contractHash!==t.contractHash?[]:i.history}}function PN(e){let t=Wj(e),i=wN({...t,maxVerifyFailures:e.maxVerifyFailures});return{...t,decision:i,eventProjection:zj(i,null)}}var ct={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:[]},cr=F("comet-native-runtime:v3:semantic-repair-budget"),Uj=[{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function AN(e){return e.skillVersion===ct.definition.metadata.version&&e.skillHash===cr||Uj.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var ua={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Hn(e){let i={sequence:(await qe(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await $w(e.changeDir,e.run.trajectoryRef,i),i}async function lr(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await Hw(e.changeDir,e.run.checkpointRef,t),t}function Hl(e){return F(JSON.stringify({summary:e.summary,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var HN=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Xj=new Set(HN),DN=new Set([...HN,"minimum_runtime_version","revision"]),Qj=new Set([...DN,"operation"]),Zj=512*1024,ph=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),eO=new Set([...ph,"implementationScopeHash","repairScopeHash","repairStagnation"]),zo=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Be(e,t){return Yj.join(C(e,t),"runtime","transition.json")}function tO(e){return`transition-${e}`}async function iO(e,t,i){let n=tO(t);return ci(e,n,i)}async function He(e,t,i,n){let r=await iO(e,t,i);try{return await n()}finally{await li(r)}}function Ml(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function gh(e,t){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function Dl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function wi(e,t){return vh(e,t)}function mh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,n=Object.keys(i),r=n.find(u=>!eO.has(u)),a=[...ph].find(u=>!Object.hasOwn(i,u)),o=ph.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0);if(r||a||n.length!==o)throw new Error(`Native transition journal event data keys are invalid${r?`: ${r}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if($n(i.summary,"Native transition journal event summary"),Ne(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&($n(i.noCodeReason,"Native transition journal event no-code reason"),Ne(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?hh(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function nO(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,n=Object.keys(i),r=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(n.length===r.size&&n.every(a=>r.has(a))&&i.reason==="spec-rebase")return mh({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return mh(e,t)}function wh(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?nO(e.eventData,e.evidenceHash):mh(e.eventData,e.evidenceHash),r=kn(e.nextRun),a=e.previousRun===null?null:kn(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function xN(e,t,i=!1){if(e.skill!==ct.definition.metadata.name||(i?!AN(e):e.skillVersion!==ct.definition.metadata.version||e.skillHash!==cr)||e.orchestration!==ct.definition.orchestration.mode||e.pendingRef!==at.pendingRef||e.trajectoryRef!==at.trajectoryRef||e.contextRef!==at.contextRef||e.artifactsRef!==at.artifactsRef||e.checkpointRef!==at.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function TN(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function _N(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function yh(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(xN(a,"next Run",n||r!==null),_N(a,"next Run"),a.runId!==t.run_id||a.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(e.run_id!==null||e.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(xN(r,"previous Run",!0),_N(r,"previous Run"),e.run_id!==r.runId||r.currentStep!==e.phase||t.run_id!==r.runId)throw new Error("Native transition journal previous Run does not match the change state");if(a.iteration!==r.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!vh(TN(r),TN(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function rO(e,t,i){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function MN(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function IN(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Nh(e,t,i,n,r=!1){let a=i.eventData,o=IN(e),s=IN(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&vh(e.spec_changes,t.spec_changes),l=Hl({summary:a.summary});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(n==="spec-rebase"){let c=rO(e.name,a.summary,t.spec_changes),l=F(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Fl(e,t){let i=Ml(e);if(gh(i,Qj),i.schema!==_i)throw new Error(`Expected Native transition schema ${_i}`);let n=Dl(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(n>3)throw new Error(`Native transition requires runtime protocol ${n}; current protocol is ${3}`);if(n!==3)throw new Error(`Native transition ${_i} minimum_runtime_version must be ${3}`);let r=Dl(i.revision,"Native transition revision");if(r!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat")throw new Error("Native transition journal operation is invalid");let a=wh(i,t),o=_t(i.previousState),s=_t(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Nh(o,s,a,i.operation),yh(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:_i,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function aO(e,t){let i=Ml(e);if(gh(i,Xj),i.schema!==er)throw new Error(`Expected Native transition schema ${er}`);let n=wh(i,t,!0),r=jo(i.previousState),a=jo(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Nh(r,a,n,MN(r,a,n.eventData),!0),yh(r,a,n,!0),{schema:er,id:n.id,change:t,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function bh(e,t){let i=Ml(e);if(gh(i,DN),i.schema!==Ii)throw new Error(`Expected Native transition schema ${Ii}`);if(Dl(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ii} minimum_runtime_version must be 2`);let r=Dl(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=wh(i,t,!0),o=Pn(i.previousState),s=Pn(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Nh(o,s,a,MN(o,s,a.eventData),!0),yh(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ii,minimum_runtime_version:2,revision:r,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function oO(e,t){let i=Ml(e);if(i.schema===_i)return{status:"current",journal:Fl(i,t)};if(i.schema===er)return{status:"migration-required",journal:aO(i,t)};if(i.schema===Ii)return{status:"migration-required",journal:bh(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Sh(e,t){let i=Be(e,t);await A(e.nativeRoot,i);try{let n=await ue({root:e.nativeRoot,file:i,maxBytes:Zj,label:`Native transition journal ${t}`});return oO(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function yi(e,t){let i=await Sh(e,t);if(!i)return null;if(i.status==="migration-required")throw new zo(t);return i.journal}async function Wo(e){if(await tr(e.paths,e.nextState.name))throw new Error(`Native schema migration is incomplete for ${e.nextState.name}; run doctor --repair`);await Co(e.paths,e.nextState.name);let t={schema:_i,minimum_runtime_version:3,revision:1,operation:e.operation??"advance",id:e.transitionId?.()??Kj(),change:e.nextState.name,evidenceHash:e.evidenceHash,createdAt:(e.now??new Date).toISOString(),previousState:e.previousState,nextState:e.nextState,previousRun:e.previousRun,nextRun:e.nextRun,eventData:e.eventData},i=Fl(t,t.change),n=Be(e.paths,i.change);if(await A(e.paths.nativeRoot,n),await yi(e.paths,i.change))throw new Error(`Native transition recovery is already pending for ${i.change}`);return await de(n,i),i}function jN(e,t){if(wi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(wi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function ON(e,t){if(wi(e,t.nextState))return"next";if(wi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function sO(e){let{journal:t}=e;return FN({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function FN(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function $N(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),n=i.filter(({event:a})=>a.type==="run_started"),r=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==n.length+r.length||n.length>(t.previousRun===null?1:0)||r.length>1||t.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=sO({sequence:a.index+1,journal:t,type:a.event.type});if(!wi(FN(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function Ni(e,t,i){if(await tr(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Co(e,t);let n=await yi(e,t);if(!n)return null;let r=C(e,t),a=$N(await qe(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([ye(r),W(e,t)]),c=jN(o,n),l=ON(s,n);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${n.change}; recovery journal was preserved`);if(c==="previous"&&(await Zn(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!wi(await ye(r),n.nextRun))throw new Error(`Native transition Run content changed while continuing ${n.change}; recovery journal was preserved`);if(l==="previous"){let v=await Gr(e,n.nextState,n.previousState.revision);if(!wi(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!wi(await W(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await yi(e,t);if(!u||!wi(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=$N(await qe(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Hn({changeDir:r,run:n.nextRun,type:"run_started",data:{runtime:"comet-native",phase:n.previousState.phase,transitionId:n.id},now:new Date(n.createdAt)}));let f=d.transitioned;f||(f=await Hn({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await lr({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([ye(r),W(e,t)]);jN(p,{...n,previousRun:n.nextRun}),ON(m,{...n,previousState:n.nextState});let h=await yi(e,t);if(!h||!wi(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await Gj.rm(Be(e,t),{force:!0}),n.nextState}async function LN(e,t,i){return re(e,`continue transition ${t}`,()=>He(e,t,`continue transition ${t}`,()=>Ni(e,t,i)))}import Rb from"node:path";import qN from"node:path";var cO="comet.native.acceptance.v1",lO=/^acceptance-[a-f0-9]{64}$/u,uO=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),dO=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,fO=/^[a-f0-9]{64}$/u,hO=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function pO(e,t){return e<t?-1:e>t?1:0}var Vi=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ko=Object.freeze({maxCriteria:1024}),Uo="<!-- comet-native:acceptance-evidence:start -->",da="<!-- comet-native:acceptance-evidence:end -->";function BN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",n=0;for(let r of e){let a=Buffer.byteLength(r,"utf8");if(n+a>t)break;i+=r,n+=a}return{value:i,truncated:!0}}function VN(e,t){let i=t.toString(36),n=H("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function mO(e){if(!fO.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=hO.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==H("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function vO(e,t){let i=BN(e.text,Vi.maxTextBytes),n=e.context.slice(0,Vi.maxContextItems).map(r=>BN(r,Vi.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:n.map(r=>r.value),text:i.value,contextTruncated:e.context.length>n.length||n.some(r=>r.truncated),textTruncated:i.truncated,verificationStatus:t}}function Ll(e){let t=mO({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(pO),r=n.slice(0,Vi.maxFailedCheckIds),a=e.criteria.slice(t,t+Vi.maxItems);for(let c of a){let l=[...i,vO(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:u<e.criteria.length?VN(e.acceptanceHash,u):null,limits:{...Vi}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Vi.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:r,failedCheckIdsTruncated:n.length>r.length,nextCursor:o<e.criteria.length?VN(e.acceptanceHash,o):null,limits:{...Vi}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Vi.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Rh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function kh(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let n=i[1][0];return t===null?{marker:n,length:i[1].length}:n===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function JN(e){return e.includes("-->")||e.includes("--!>")}function*fa(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
194
194
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
195
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&n===null,index:s},s+=1,t!==null)t=kh(l,t);else if(i)JN(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=kh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!JN(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&r.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function vO(e){return[...fa(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Eh(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function gO(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Ch(e,t,i,n=[]){let r=Eh(i),a=t.replaceAll("\\","/").trim(),o=n.map(Eh);if(r.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:`acceptance-${H(sO,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Ph(e,t){let i=new Set;for(let n of e){if(i.has(n.id))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(n.id)}return e}function wO(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of fa(e)){r=s+1;let c=o?Rh(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(n+=1,n===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??r}}function zN(e,t="brief.md",i=Ko.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=wO(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of fa(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(d===null)continue;let f=d[1].length;r=r===null?f:Math.min(r,f)}let a=[],o=null,s=()=>{if(o!==null){if(a.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);a.push(o)}};for(let{line:c,body:l,index:u}of fa(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;d&&d[1].length===r?(s(),o=[d[2]]):o!==null&&o.push(c)}return s(),Ph(a.map(c=>Ch("brief-example",t,c.join(`
195
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&n===null,index:s},s+=1,t!==null)t=kh(l,t);else if(i)JN(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=kh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!JN(f))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&r.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function gO(e){return[...fa(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Eh(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function wO(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function Ch(e,t,i,n=[]){let r=Eh(i),a=t.replaceAll("\\","/").trim(),o=n.map(Eh);if(r.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:`acceptance-${H(cO,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function Ph(e,t){let i=new Set;for(let n of e){if(i.has(n.id))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(n.id)}return e}function yO(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of fa(e)){r=s+1;let c=o?Rh(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(n+=1,n===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(n===0||t===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??r}}function zN(e,t="brief.md",i=Ko.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=yO(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of fa(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(d===null)continue;let f=d[1].length;r=r===null?f:Math.min(r,f)}let a=[],o=null,s=()=>{if(o!==null){if(a.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);a.push(o)}};for(let{line:c,body:l,index:u}of fa(e)){if(u<n.start||u>=n.end)continue;let d=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;d&&d[1].length===r?(s(),o=[d[2]]):o!==null&&o.push(c)}return s(),Ph(a.map(c=>Ch("brief-example",t,c.join(`
196
196
  `))),"Brief")}function WN(e,t="spec.md",i=Ko.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=()=>{if(a!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Ch("spec-scenario",t,[a.title,...a.body].join(`
197
- `),a.context)),a=null}};for(let{line:s,body:c}of fa(e)){let l=c?Rh(s):null,u=l?/^Scenario\s*:\s*(.*)$/iu.exec(l.text):null;if(u){for(o();r.at(-1)&&r.at(-1).level>=l.level;)r.pop();let d=Eh(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:d,body:[],context:r.map(f=>f.text)}}else if(l){for(a!==null&&l.level<=a.level?o():a!==null&&a.body.push(s);r.at(-1)&&r.at(-1).level>=l.level;)r.pop();r.push(l)}else a!==null&&c&&a.body.push(s)}return o(),Ph(n,"Specification")}function UN(e,t="spec.md",i=Ko.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Ch("spec-must",t,o.parts.join(" "),o.context)),o=null}},c=()=>r.some(l=>/^(?:non-?goals?|非目标)$/iu.test(l.text.trim()));for(let{line:l,body:u}of fa(e)){let d=u?Rh(l):null;if(d){for(s(),a!==null&&d.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=d.level;)r.pop();r.push(d),/^Scenario\s*:/iu.test(d.text)&&(a=d.level);continue}let f=l.trim();if(!u||a!==null||c()){s();continue}if(f.length===0||kh(l,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){s();continue}let p=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(p){s(),o={parts:[p[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Ph(n,"Specification mandatory requirements")}function yO(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||gO(i)||qN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=qN.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!uO.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function NO(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!lO.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function KN(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=NO(i,n),a=r.acceptance_id;if(typeof a!="string"||!cO.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(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 yO(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 ql(e){let t=vO(e);if(t.some(({line:l,body:u})=>!u&&(l===Uo||l===da)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===Uo?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===da?[d]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
197
+ `),a.context)),a=null}};for(let{line:s,body:c}of fa(e)){let l=c?Rh(s):null,u=l?/^Scenario\s*:\s*(.*)$/iu.exec(l.text):null;if(u){for(o();r.at(-1)&&r.at(-1).level>=l.level;)r.pop();let d=Eh(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:d,body:[],context:r.map(f=>f.text)}}else if(l){for(a!==null&&l.level<=a.level?o():a!==null&&a.body.push(s);r.at(-1)&&r.at(-1).level>=l.level;)r.pop();r.push(l)}else a!==null&&c&&a.body.push(s)}return o(),Ph(n,"Specification")}function UN(e,t="spec.md",i=Ko.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],r=[],a=null,o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(Ch("spec-must",t,o.parts.join(" "),o.context)),o=null}},c=()=>r.some(l=>/^(?:non-?goals?|非目标)$/iu.test(l.text.trim()));for(let{line:l,body:u}of fa(e)){let d=u?Rh(l):null;if(d){for(s(),a!==null&&d.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=d.level;)r.pop();r.push(d),/^Scenario\s*:/iu.test(d.text)&&(a=d.level);continue}let f=l.trim();if(!u||a!==null||c()){s();continue}if(f.length===0||kh(l,null)!==null||f.startsWith("<!--")||f==="-->"||f==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(f)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(f)||/^(?:[-*_]\s*){3,}$/u.test(f)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(f)){s();continue}let p=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(l);if(p){s(),o={parts:[p[1]],context:r.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(f)){s(),o={parts:[f],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[f],context:r.map(m=>m.text)}:o.parts.push(f)}return s(),Ph(n,"Specification mandatory requirements")}function NO(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||wO(i)||qN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let n=qN.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!dO.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function bO(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,n=Object.keys(i).filter(r=>!uO.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function KN(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,n)=>{let r=bO(i,n),a=r.acceptance_id;if(typeof a!="string"||!lO.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(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 NO(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 ql(e){let t=gO(e);if(t.some(({line:l,body:u})=>!u&&(l===Uo||l===da)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===Uo?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===da?[d]:[]);if(n.length!==1||r.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(n[0]>=r[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
198
198
  `).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=KN(o),c=GN(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function GN(e){let t=KN([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(t,null,2)}function Bl(e){return[Uo,GN(e),da].join(`
199
- `)}import YN from"node:path";var bO="comet.native.contract.v1",SO="comet.native.acceptance-set.v1",XN=/^[a-f0-9]{64}$/u,Go={maxAcceptanceCriteria:Ko.maxCriteria};function QN(e,t){let i=YN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||YN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function ZN(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
200
- `))}function kO(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(XN))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(XN))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=QN(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:ZN(e.markdown)},markdown:e.markdown}}function EO(e,t){return eb(e.id,t.id)}function eb(e,t){return e<t?-1:e>t?1:0}function tb(e){let t=QN(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(kO).sort((d,f)=>eb(d.snapshot.capability,f.snapshot.capability)),n=i.map(({snapshot:d})=>d.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=zN(e.briefMarkdown,t,Go.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...WN(f,d.source,Go.maxAcceptanceCriteria-a.length)),a.push(...UN(f,d.source,Go.maxAcceptanceCriteria-a.length)));if(a.sort(EO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Go.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Go.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:ZN(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(SO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(bO,u)}}var Yt={maxSpecs:64,maxFileBytes:eo,maxTotalBytes:4*1024*1024};async function bt(e){if(e.specChanges.length>Yt.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ge({root:e.changeDir,ref:e.briefRef,maxBytes:Yt.maxFileBytes}),i=t.size,n=[];for(let r of e.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await ge({root:e.changeDir,ref:r.source,maxBytes:Yt.maxFileBytes});if(i+=a.size,i>Yt.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:tb({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as DO,spawn as Lh}from"node:child_process";import{createHash as MO}from"node:crypto";import{existsSync as yb}from"node:fs";import bi from"node:path";import{promisify as FO}from"node:util";import{spawn as RO}from"node:child_process";import Ah from"node:path";var CO=1e3,PO=2;async function ib(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Ah.win32.isAbsolute(i)?Ah.win32.resolve(i):"C:\\Windows",r=Ah.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=RO(r,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),CO)}catch{u(!1)}});for(let o=0;o<PO;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}import{randomUUID as xO}from"crypto";import{promises as TO}from"fs";import ha from"path";var Xt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pa=/^[a-f0-9]{64}$/u;function Vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jl(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Dn(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function nb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rb(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||ha.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=ha.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Th(e,t){return ha.join(C(e,t),"runtime","checkpoints","progress.json")}function Ji(e,t){return ha.join(C(e,t),"runtime","checkpoint-journal.json")}function _h(e,t,i){if(!pa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return ha.join(C(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function Ih(e){if(!pa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function jh(e,t,i){let n=await ue({root:e,file:t,maxBytes:Xt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function AO(e,t){let i=Vl(e,`checkpoint manifest artifact ${t}`);Jl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=rb(Dn(i.path,`checkpoint artifact ${t} path`,4096)),r=ai(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!pa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:xh(i.size,`checkpoint artifact ${t} size`)}}function zl(e,t){let i=Vl(e,"Native checkpoint manifest");if(Jl(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Xt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(AO),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=xh(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Xt.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:n,totalBytes:a}}function Yo(e){return F(JSON.stringify(zl(e,e.change)))}function Oh(e,t){let i=Vl(e,"Native progress checkpoint");if(Jl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=nb(i.previousRevision,"Native checkpoint previousRevision"),a=nb(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Dn(i.manifestHash,"Native checkpoint manifestHash",64);if(!pa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=Ih(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Dn(i.inputHash,"Native checkpoint inputHash",64);if(!pa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Dn(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=xh(i.artifactCount,"Native checkpoint artifactCount");if(u>Xt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Dn(i.summary,"Native checkpoint summary"),f=Dn(i.nextAction,"Native checkpoint nextAction");if(Ne(d)!==d||Ne(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Dn(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function ab(e,t){let i=Vl(e,"Native checkpoint journal");if(Jl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=_t(i.previousState),r=_t(i.nextState),a=Oh(i.checkpoint,t),o=zl(i.manifest,t),s=Dn(i.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==Yo(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function ob(e,t,i){let n=ha.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,n)||$(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=Za(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ue({root:e.projectRoot,file:n,maxBytes:Xt.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function sb(e,t,i,n){let r=i.map(rb).sort();if(r.length>Xt.maxArtifacts)throw new Error(`Checkpoint supports at most ${Xt.maxArtifacts} artifacts`);if(new Set(r).size!==r.length)throw new Error("Checkpoint artifacts must not contain duplicates");let a=[],o=0;for(let s of r){let c=await ob(e,s,n);if(o+=c.size,o>Xt.maxTotalBytes)throw new Error("Checkpoint artifacts exceed the total byte budget");a.push(c)}return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:a,totalBytes:o}}async function $h(e,t){let i=Th(e,t);await A(e.nativeRoot,i);try{return Oh(await jh(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Hh(e,t,i){let n=_h(e,t,i);await A(e.nativeRoot,n);let r=await jh(e.nativeRoot,n,"Native checkpoint manifest"),a=zl(r,t);if(Mh(e,a),Yo(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function zi(e,t){let i=Ji(e,t);await A(e.nativeRoot,i);try{let n=ab(await jh(e.nativeRoot,i,"Native checkpoint journal"),t);return Mh(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Dh(e,t,i,n){let r=zl(i,t);Mh(e,r);let a=Yo(r),o=_h(e,t,a);await A(e.nativeRoot,o);try{let s=await Hh(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await de(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Mh(e,t){for(let i of t.artifacts){let n=Za(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function cb(e,t){let i=Oh(t,t.change),n=await Hh(e,i.change,i.manifestHash),r=F(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Th(e,t.change);await A(e.nativeRoot,a),await de(a,i,{containedRoot:e.nativeRoot})}async function lb(e,t){let i=ab(t,t.change),n=Ji(e,t.change);if(await A(e.nativeRoot,n),await zi(e,t.change))throw new Error(`Native checkpoint recovery is already pending for ${t.change}`);await de(n,i,{containedRoot:e.nativeRoot})}async function ub(e){let t;try{t=await $h(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Th(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],n=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let r=null;try{r=await Hh(e.paths,e.name,t.manifestHash);let a=F(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:r.artifacts}));if(t.inputHash!==a||t.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of r.artifacts)try{let s=await ob(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),n.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:_h(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function db(e){let t=(e.now??new Date).toISOString(),i=e.checkpointId?.()??xO(),n={...e.checkpoint,id:i,createdAt:t},r={schema:"comet.native.checkpoint-journal.v1",id:i,change:e.previousState.name,inputHash:n.inputHash,createdAt:t,previousState:e.previousState,nextState:e.nextState,checkpoint:n,manifest:e.manifest};return await Dh(e.paths,e.previousState.name,e.manifest),await lb(e.paths,r),r}async function Xo(e,t,i){let n=await zi(e,t);if(!n)return null;if(await Dh(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Gr(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await cb(e,n.checkpoint),await i?.afterProgressWritten?.(n),await TO.rm(Ji(e,t),{force:!0}),n}async function fb(e,t,i){return re(e,`continue checkpoint ${t}`,()=>He(e,t,`continue checkpoint ${t}`,async()=>(await Ni(e,t),Xo(e,t,i))))}async function St(e,t){await Ni(e,t),await Xo(e,t)}import{constants as Fh,promises as Ot}from"node:fs";import ur from"node:path";var _O=/^[a-f0-9]{64}$/u,IO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,dr=512*1024;function jO(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function OO(e,t){let i=ur.resolve(e),n=ur.resolve(t);if(!$(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...ur.relative(i,n).split(ur.sep).filter(Boolean)]){o&&(a=ur.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function hb(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!jO(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function pb(e){if(!_O.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function $O(e){let t=IO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function mb(e,t,i){return ur.join(C(e,t),...pb(i).split("/"))}async function HO(e,t,i){let n=await OO(i,ur.dirname(e)),r=await Ot.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>dr)throw new Error(`Native check receipt exceeds ${dr} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Fh.O_RDONLY|Fh.O_NOFOLLOW|Fh.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await hb(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Wl(r,l)||!Wl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let E=dr+1-p,N=await c.read(m,0,Math.min(m.length,E),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>dr)throw new Error(`Native check receipt exceeds ${dr} bytes`);f.push(Buffer.from(m.subarray(0,N.bytesRead)))}let[h,v,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await hb(n),!v.isFile()||v.isSymbolicLink()||b!==o||!$(a,b)||!Wl(l,h)||!Wl(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Ul(e,t,i){let n=$O(i),r=C(e,t),a=mb(e,t,n);await A(e.nativeRoot,a);let o=Li(await HO(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}async function vb(e){let t=Li(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let i=pb(t.receiptHash),n=mb(e.paths,e.name,t.receiptHash);if(Buffer.byteLength(JSON.stringify(t,null,2)+`
201
- `,"utf8")>dr)throw new Error(`Native check receipt exceeds ${dr} bytes`);await A(e.paths.nativeRoot,n);try{let o=await Ul(e.paths,e.name,i);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await de(n,t,{containedRoot:e.paths.nativeRoot});let a=await Ul(e.paths,e.name,i);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return i}var qh=64*1024,LO=12e4,Qo=3600*1e3,qO=4e3,BO="native-runtime:manual-evidence",gb=FO(DO),VO=new Set([".bat",".cmd",".ps1"]),JO=["$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("; ");function zO(e){let t=(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function WO(e,t,i){let r=bi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(t.PATH??"").split(bi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=bi.win32.extname(e)?[e]:zO(t).map(s=>`${e}${s}`);return r.flatMap(s=>o.map(c=>s?bi.join(s,c):bi.resolve(i,c)))}function UO(e,t,i){return WO(e,t,i).find(n=>yb(n))??e}function KO(e){let t=e.SYSTEMROOT??e.SystemRoot;if(t){let i=bi.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(yb(i))return i}return"powershell.exe"}function GO(e,t,i){let n=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),r=Buffer.from(JO,"utf16le").toString("base64");return Lh(KO(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function YO(e,t,i){if(process.platform!=="win32")return Lh(e,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=UO(e,i.env,i.cwd);return VO.has(bi.win32.extname(n).toLowerCase())?GO(n,t,i):Lh(n,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function Nb(e){return re(e.paths,e.operation,()=>He(e.paths,e.name,e.operation,async()=>(await St(e.paths,e.name),e.issue(await W(e.paths,e.name)))))}function XO(e,t){let i=e.trim();if(!i||Buffer.byteLength(i,"utf8")>qh)throw new Error(`${t} is invalid`);return i}function bb(e,t){let i=[...e].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!t.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Zo(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([gi(e,t.name,t.implementation_scope),bt({changeDir:C(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=t.run_id?`run:${t.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:Rl(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var QO=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Kl(e,t){let i=[];for(let n of QO){let r=e.bindings[n],a=t[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function Sb(e){let t=await Zo(e.paths,e.state),i=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=e.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=El({kind:"static-inspection",role:"required-check",status:n,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:t.scope.scope.changes.map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await xl({paths:e.paths,name:e.state.name,receipt:r});return{receipt:r,ref:a}}async function Gl(e){return Nb({paths:e.paths,name:e.name,operation:`issue manual receipt ${e.name}`,issue:t=>ZO({...e,state:t})})}async function ZO(e){let t=await Zo(e.paths,e.state),i=El({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:t.bindings,acceptanceIds:bb(e.acceptanceIds,t.acceptanceIds),actor:BO,issuedAt:(e.now??new Date).toISOString(),evidence:{steps:[...e.steps],observations:[...e.observations]}});return{receipt:i,ref:await xl({paths:e.paths,name:e.state.name,receipt:i})}}function e$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function t$(e){let t=e$(e.context.scope.baseline),i=await bn(e.paths,t,{origin:"explicit",now:e.now}),n=Tn({baseline:t,current:i,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths});return{snapshotHash:n.scope.currentProjectionHash,scopeHash:n.scope.scopeHash,matched:n.scope.currentProjectionHash===e.context.bindings.snapshotHash&&n.scope.scopeHash===e.context.bindings.scopeHash}}async function wb(e){try{let[{stdout:t},{stdout:i}]=await Promise.all([gb("git",["-C",e,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),gb("git",["-C",e,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=bi.resolve(t.trim()),r=bi.relative(e,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||bi.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function kb(e){return Nb({paths:e.paths,name:e.name,operation:`issue automated receipt ${e.name}`,issue:t=>i$({...e,state:t})})}async function i$(e){let t=await Zo(e.paths,e.state),i=await wb(e.paths.projectRoot),n=(e.now?.()??new Date).toISOString(),r=e.timeoutMs??LO;if(!Number.isSafeInteger(r)||r<1||r>Qo)throw new Error(`Native automated command timeout must be an integer from 1 through ${Qo}`);let a=[],o=0,s=0,c=MO("sha256"),l=!1,u=YO(e.command,e.args,{cwd:e.paths.projectRoot,env:{...process.env}}),d=w=>{if(c.update(w),s+=w.byteLength,o>=qh)return;let y=qh-o,g=w.subarray(0,y);a.push(Buffer.from(g)),o+=g.byteLength};u.stdout.on("data",d),u.stderr.on("data",d);let f=await new Promise((w,y)=>{let g=!1,k=null,x=null,U=z=>{g||(g=!0,clearTimeout(D),x&&clearTimeout(x),w(z))},D=setTimeout(()=>{l=!0,k=ib(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),x=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),U({exitCode:124,signal:"SIGKILL"})},qO)},r);u.once("error",z=>{if(l){(k??Promise.resolve()).then(()=>U({exitCode:124,signal:"SIGKILL"}));return}g||(g=!0,clearTimeout(D),x&&clearTimeout(x),y(z))}),u.once("close",(z,ne)=>{(k??Promise.resolve()).then(()=>U({exitCode:l?124:z??1,signal:ne??(l?"SIGKILL":null)}))})}),p=(e.now?.()??new Date).toISOString(),[m,h]=await Promise.all([wb(e.paths.projectRoot),t$({paths:e.paths,context:t,now:e.now?.()})]),v=t.scope.current.capture,E=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,N=l||!h.matched||!E?"blocked":f.exitCode===0?"passed":"failed",S=Buffer.concat(a,o).toString("utf8").trim(),R=El({kind:"automated-check",role:"acceptance-evidence",status:N,bindings:t.bindings,acceptanceIds:bb(e.acceptanceIds,t.acceptanceIds),actor:`native-runtime:command:${e.command}`,issuedAt:p,evidence:{executable:e.command,args:[...e.args],cwd:".",exitCode:f.exitCode,signal:f.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:p,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{...h,matched:h.matched&&E},outputHash:c.digest("hex"),outputSummary:XO(Ne(S||`(exit ${f.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:R,ref:await xl({paths:e.paths,name:e.state.name,receipt:R})}}async function Eb(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Ul(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Wi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function n$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}function r$(e){let t=Rb.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/");if(!t||t===".."||t.startsWith("../")||Rb.posix.isAbsolute(t))throw new Error("Native root is outside the project root");return t}async function a$(e){let t=n$(e.bundle.baseline),i=await bn(e.paths,t,{origin:"explicit",now:e.now});return Tn({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function Vh(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await gi(e.paths,e.state.name,e.state.implementation_scope),i=await bt({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await a$({paths:e.paths,bundle:t,now:e.now}),r=[];return i.contract.contractHash!==t.scope.contractHash&&r.push("verification-contract-stale"),n!==t.scope.currentProjectionHash&&r.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:r}}async function es(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Vh(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function Pb(e){let t=await ge({root:C(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:ql(t.text)}}function o$(e){let{receipt:t,implementationScope:i}=e,n=[],r=i.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==r.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==r.length||t.counts.bytesScanned!==a))&&n.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&n.push("verification-receipt-outcome-mismatch"),n}function s$(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Rl(e.implementationScope.scope.declaredArtifacts)}}async function Cb(e){let t=await oa(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Kl(t,e.expectedBindings);if(i.push(...n.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Wi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let r=await Eb({paths:e.paths,state:e.state,receipt:t});if(r){let a=o$({receipt:r,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function Ab(e){let t=s$({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Cb({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Wi)return i.push(...a.details),null;throw a});if(r!==null&&r.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let n of e.trace.entries)if(n.status!=="missing")for(let r of n.evidenceRefs){let a=await Cb({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Wi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(n.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Wi(i)}async function xb(e){if(e.state.phase!=="verify")throw new Error(`Native verification evidence requires Verify, got ${e.state.phase}`);let t=await Vh(e);if(t.findingCodes.length>0)return{ready:!1,findingCodes:t.findingCodes,envelope:null,evidenceRef:null,reportSnapshot:null};let i=await Pb(e);if(e.result==="pass"&&!e.receiptRef)throw new Error("Native passing verification requires a typed required-check receipt");let n=e.receiptRef?[e.receiptRef]:[],r=My(t.contract.acceptance,i.entries,{nativeRootRef:r$(e.paths),allowMissing:e.result==="fail"});if(e.result==="pass"&&r.entries.some(c=>c.status==="failed"||c.status==="missing"))throw new Error("Native passing verification cannot include failed or missing acceptance criteria");try{await Ab({paths:e.paths,state:e.state,result:e.result,trace:r,requiredReceiptRefs:n,contractHash:t.contractHash,implementationScope:t.bundle})}catch(c){if(c instanceof Wi)return{ready:!1,findingCodes:["verification-receipt-binding-mismatch"],envelope:null,evidenceRef:null,reportSnapshot:null,...c.details.length>0?{receiptBindingFailures:c.details}:{}};throw c}let a=e.state.partial_allowance?await lh(e.paths,e.state.name,e.state.partial_allowance):null,o=Ly({change:e.state.name,sourceRevision:e.state.revision,result:e.result,contractHash:t.contractHash,acceptanceHash:t.acceptanceHash,implementationScope:{ref:e.state.implementation_scope,bundle:t.bundle},reportRef:i.ref,reportHash:i.hash,requiredReceiptRefs:n,acceptanceTrace:r,partialAllowance:e.state.partial_allowance&&a?{ref:e.state.partial_allowance,allowance:a}:null,now:e.now}),s=wt("verifications",o.envelopeHash);return{ready:!0,findingCodes:[],envelope:o,evidenceRef:s,reportSnapshot:{hash:i.hash,text:i.text}}}async function Tb(e){if(!e.preparation.ready||e.preparation.envelope===null||e.preparation.evidenceRef===null||e.preparation.reportSnapshot===null)throw new Error("Native verification evidence is not ready to persist");if(await oN({paths:e.paths,name:e.state.name,...e.preparation.reportSnapshot}),await hN({paths:e.paths,name:e.state.name,evidence:e.preparation.envelope})!==e.preparation.evidenceRef)throw new Error("Native verification evidence persistence ref changed")}function Bh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function fr(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Bh(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Vh(e),On(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Bh(e.state.verification_result,"stale"),envelope:null};let n=await Pb({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),r=[...t.findingCodes];(n.hash!==i.reportHash||n.ref!==i.reportRef)&&r.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&r.push("verification-state-mismatch");try{await Ab({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{r.push("verification-receipt-invalid")}let a=[...new Set(r)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Bh(e.state.verification_result,"invalid"),envelope:null}}}function l$(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Ib(e){try{return await c$.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function u$(e,t){try{return(await ge({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function d$(e,t,i){let n=Jt(e,i.capability);if(!$(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=_b.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await u$(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ge({root:C(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function f$(e,t){return Ib(Be(e,t))}async function hr(e){let t=e.now??new Date,i=await W(e.paths,e.name),n=await le(e.paths.projectRoot),r=l$(i.name,t),a=_b.resolve(e.paths.nativeRoot,...r.split("/"));if(!$(e.paths.nativeRoot,a))throw new Error("Native archive target escapes its root");let[o,s,c,l,u,d,f]=await Promise.all([Promise.all(i.spec_changes.map(p=>d$(e.paths,i.name,p))),fr({paths:e.paths,state:i,now:t}),Tl(e.paths,i.name),tr(e.paths,i.name),Kr(e.paths,i.name),f$(e.paths,i.name),Ib(a)]);return uy({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:l||u||d,targetRef:r,targetExists:f,specs:o,evidence:s.evidence,findingCodes:[...s.findingCodes,...c.findingCodes]})}import{promises as Jh}from"node:fs";import Ui from"node:path";var h$="comet.native.archive-tree.v1",p$={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function $b(e){let t={...p$,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function jb(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Ob(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function Hb(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await pt({root:e,directory:t,label:`Native Archive content directory ${Ui.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=jb(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ui.join(t,u.name),f=Ui.relative(e,d).replaceAll("\\","/"),p=await Jh.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){Ob(i,{ref:f,kind:"directory"},n,r),await Hb(e,d,i,n,r,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ue({root:e,file:d,maxBytes:r.maxFileBytes,label:`Native Archive content file ${f}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);Ob(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await pt({root:e,directory:t,label:`Native Archive content directory ${Ui.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(jb(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ui.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function zh(e,t={}){let i=$b(t);e=Ui.resolve(e);let n=await Jh.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await Hb(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return F(`${h$}\0${o}`)}async function Qt(e,t={}){let i=$b(t);e=Ui.resolve(e);let n;try{n=await Jh.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await ue({root:Ui.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ui.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await zh(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Je}from"node:fs";import be from"node:path";var Uh=16*1024*1024,m$=256*1024,v$=16*1024,ts="comet.native.archive-cas.v1";function g$(e,t){let i=be.resolve(e.nativeRoot,...t.split("/"));if(be.relative(e.nativeRoot,i).split(be.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Ve(e,t){return A(e.nativeRoot,g$(e,t))}function Mn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ma(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function lt(e){let t=await Qt(e.target);if(!Mn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ma(t)}`);return t}async function qb(e,t){let i=go(t),n=await Pt(e,i.id);await Je.mkdir(n.staged,{recursive:!0}),await Je.mkdir(n.backups,{recursive:!0}),await de(n.journal,i,{containedRoot:e.nativeRoot}),await mt(e,i.id,"prepared")}async function Kh(e,t){let i=await Pt(e,t),n=await ue({root:e.nativeRoot,file:i.journal,maxBytes:m$,label:`Native Archive transaction journal ${t}`}),r=go(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function Yl(e,t,i){let n=go({...t,status:i}),r=await Pt(e,n.id);return await de(r.journal,n,{containedRoot:e.nativeRoot}),n}function Xl(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Db(e){return{...Xl(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fn(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function w$(e,t){return Fn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ce(e){try{return await Je.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Si(e){let t=await Je.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=Db(t),n=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:Uh,label:e.label}),r=await Je.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!w$(i,Db(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Xl(r),size:n.size}}function y$(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==ts||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ts,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function ki(e,t,i,n){let r=await Pt(e,t.id),a=be.join(r.backups,".cas"),o=`.${be.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:be.join(a,`${i.id}.original.json`),postRecord:be.join(a,`${i.id}.post.json`),candidate:be.join(a,`${i.id}.candidate`),originalQuarantine:be.join(be.dirname(n),`${o}.original`),rollbackQuarantine:be.join(be.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>A(e.nativeRoot,c))),s}async function $t(e){if(!await ce(e.file))return null;let t=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:v$,label:`Archive CAS ${e.operation.id} ${e.role} record`});return y$(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Ql(e){let t=await $t(e);if(t){if(!Fn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await di({root:e.paths.nativeRoot,directory:be.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ts,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await de(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await $t(e);if(!n||!Fn(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function Ae(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Fn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function N$(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Ql({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Ae({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function b$(e){if(!await ce(e.quarantine)||await ce(e.target))return;let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Je.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([Je.lstat(e.quarantine),Je.lstat(e.target)]);if(!Fn(Xl(i),Xl(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Je.unlink(e.quarantine),await t.verify()}async function Bb(e){if(await ce(e.quarantine)){await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Ae({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Ae({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Je.rename(e.target,e.quarantine),await t.verify(),await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await b$(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function pr(e){if(!await ce(e.file))return;await Ae(e);let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.file),label:e.label});await t.verify(),await Ae(e),await Je.unlink(e.file),await t.verify()}async function Mb(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Ve(e,t.target),r=await Ve(e,t.backup),a=await Qt(r);if(a!==null){if(!Mn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await lt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ai({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:Uh,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await lt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function Vb(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await ki(e.paths,e.journal,e.operation,e.target),n=await $t({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ce(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Ae({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await Mb(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await ce(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await N$({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Ae({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await Mb(e.paths,e.operation,e.hooks),await Bb({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function Fb(e){let t=await ki(e.paths,e.journal,e.operation,e.target);return await ce(t.candidate)?(await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await di({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ai({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:Uh,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function S$(e){let t=e.operation.stagedHash,i=await ki(e.paths,e.journal,e.operation,e.target),n=await $t({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await ce(e.target))return await Ae({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await ce(i.candidate)&&await pr({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await ce(e.target)){let c=await Fb(e),l=await Si({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await Ql({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await pr({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await Fb(e),a=await Si({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await di({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Ae({paths:e.paths,file:r,operation:e.operation,record:{schema:ts,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Je.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await Ql({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await pr({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function k$(e,t,i,n){let r=await Ve(e,i.target),a=await Ve(e,i.staged);if(await lt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await ki(e,t,i,r);(!await $t({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ce(r))&&await Vb({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await Qt(r);if(o!==null&&!Mn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ma(o)}`)}await S$({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await lt({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function E$(e,t,i,n){let r=await Ve(e,i.target);await Vb({paths:e,journal:t,operation:i,target:r,hooks:n}),await lt({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function R$(e,t){let i=await Ve(e,t.source),n=await Ve(e,t.target),[r,a]=await Promise.all([Qt(i),Qt(n)]);if(!(r===null&&Mn(a,t.expectedSourceHash,"directory"))){if(!Mn(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ma(r)}, target=${ma(a)}`);await Je.mkdir(be.dirname(n),{recursive:!0}),await Je.rename(i,n),await lt({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function C$(e,t,i,n){return i.type==="write"?k$(e,t,i,n):i.type==="remove"?E$(e,t,i,n):R$(e,i)}function P$(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function A$(e,t,i,n){let r=await Ve(e,i.target);if(i.type==="write"){let a=await Ve(e,i.staged);await lt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await ki(e,t,i,r),s=await $t({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Ae({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await lt({target:await Ve(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await $t({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ce(o.originalQuarantine))await Ae({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await lt({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await lt({target:await Ve(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await ki(e,t,i,r),o=await $t({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ce(a.originalQuarantine))await Ae({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await lt({target:await Ve(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await lt({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Jb(e,t,i){let n=t.status==="prepared"?await Yl(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await vn(e,n.id),a=P$({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await A$(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await mt(e,n.id,"operation-started",l.id),await C$(e,n,l,i),await mt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await Kh(e,n.id),n}async function x$(e){try{return await Ae(e),!0}catch{return!1}}async function T$(e){await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Je.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Ae({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Wh(e){if(e.operation.type!=="write")return;let t=await ki(e.paths,e.journal,e.operation,e.target);if(!await ce(t.candidate))return;let i=await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await pr({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ts,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function _$(e,t,i,n){let r=await Ve(e,i.target),a=await ki(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await $t({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await $t({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ce(a.candidate)&&await ce(r)){let l=await Si({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Si({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Fn(l.identity,u.identity)&&(c=await Ql({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ce(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Ae({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ce(r)&&!(s!==null&&await x$({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Qt(r);if(Mn(u,o)){await Wh({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await Bb({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await ce(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ce(r)){if(!s||!await ce(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await T$({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await ce(a.originalQuarantine)&&await pr({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ce(a.rollbackQuarantine)&&await pr({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Wh({paths:e,journal:t,operation:i,target:r}),await lt({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function I$(e,t){let i=await Ve(e,t.source),n=await Ve(e,t.target),[r,a]=await Promise.all([Qt(i),Qt(n)]);if(!(Mn(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!Mn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ma(r)}, target=${ma(a)}`);await Je.mkdir(be.dirname(i),{recursive:!0}),await Je.rename(n,i)}}async function zb(e,t,i){let n=await vn(e,t.id);if(n.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Yl(e,t,"rolling-back");await mt(e,r.id,"rollback-started");let a=new Set(n.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...r.operations].reverse())a.has(o.id)&&(o.type==="move"?await I$(e,o):await _$(e,r,o,i));return await mt(e,r.id,"rollback-completed"),r=await Yl(e,r,"rolled-back"),r}async function Lb(e,t,i){let n=await Ve(e,i.target);if(i.type==="write"){let r=await ki(e,t,i,n),a=await $t({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Ae({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await lt({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function j$(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Ve(e,i.target),r=await ki(e,t,i,n);if(await ce(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await Lb(e,t,i),i.expectedTargetHash!==null){let a=await $t({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ce(r.originalQuarantine)&&await pr({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Wh({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await Lb(e,t,i)}async function Zl(e,t,i){return i==="commit"&&await j$(e,t),await mt(e,t.id,i),i==="commit"?Yl(e,t,"committed"):t}import{randomUUID as O$}from"crypto";import{promises as is}from"fs";import Ub from"path";var Gh="comet.selection.v2",$$=16*1024;function ns(e){return Ub.join(e,".comet","current-change.json")}function H$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wb(e){return e===null||typeof e=="string"}function Kb(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!H$(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Wb(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Gh,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Gh)throw new Error(`current change selection schema must be ${Gh}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Wb(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Yh(e){let t;try{let n=ns(e),{bytes:r}=await un(n,$$,{label:"current change selection"});t=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",...Kb(t)}}async function Gb(e,t){let i=Kb(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let n=ns(e),r=`${n}.${O$()}.tmp`;await is.mkdir(Ub.dirname(n),{recursive:!0});try{await is.writeFile(r,`${JSON.stringify(i.selection,null,2)}
202
- `,"utf8"),await is.rename(r,n)}catch(a){throw await is.rm(r,{force:!0}),a}}async function Yb(e){await is.rm(ns(e),{force:!0})}async function Xb(e,t,i){let n=await Yh(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await Yb(e),!0)}var cJ=16*1024;async function rs(e){let t=await Yh(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Vt(t.selection.change),t.selection)}function Qb(e){return ns(e.projectRoot)}async function eu(e,t){return re(e,`select change ${t}`,async()=>{Vt(t),await W(e,t),await Gb(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Zb(e){let t=await rs(e);return t?(await W(e,t.change),t.change):null}async function eS(e,t){return await $r(e.projectRoot),Xb(e.projectRoot,"native",t)}var L$=16*1024*1024,as=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"},va=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"};async function q$(e){try{return await rt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function B$(e){if(e.phase!=="archive")throw new Error(`Native change ${e.name} is not in Archive`);if(e.verification_result!=="pass")throw new Error(`Native change ${e.name} has not passed verification`);if(!e.verification_report)throw new Error(`Native change ${e.name} has no verification report`);if(e.archived)throw new Error(`Native change ${e.name} is already archived`)}async function V$(e,t){let i=C(e,t.name),n=await ir(i,t.brief),r=await Yr(i,t.verification_report),a=[...n.findings,...r.findings];if(a.length>0)throw new Error(`Native archive artifacts are invalid: ${a[0].message}`)}async function J$(e,t){let i=Jt(e,t.capability);await A(e.nativeRoot,i);let n=await q$(i),r=t.operation==="create"?null:t.base_hash;if(n!==r)throw new as(t.capability,r,n,i)}function z$(e,t,i){return Ei.join(e.archiveDir,`${i.toISOString().slice(0,10)}-${t}`)}async function W$(e){try{return await M$.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function U$(e){let{paths:t,state:i,now:n,transactionId:r,preflight:a}=e,o=z$(t,i.name,n);if(await W$(o))throw new Error(`Native archive target already exists: ${o}`);if(xi(t,o)!==a.targetRef)throw new Error("Native Archive target changed after preflight");let s=await Pt(t,r),c=[];for(let[u,d]of i.spec_changes.entries()){await J$(t,d);let f=Jt(t,d.capability),p=a.operations.find(S=>S.capability===d.capability&&S.operation===d.operation);if(!p)throw new Error(`Native Archive preflight has no operation for ${d.capability}`);if(d.operation!=="remove"&&p.proposedHash===null)throw new Error(`Native Archive preflight has no proposed hash for ${d.capability}`);let m=Ei.join(s.backups,"specs",d.capability,"spec.md");if(d.operation==="remove"){c.push({id:`spec-${u+1}-${d.capability}`,type:"remove",target:xi(t,f),backup:xi(t,m),expectedTargetHash:d.base_hash});continue}let h=C(t,i.name);await sy(h,d.source);let v=Ei.resolve(h,...d.source.split(/[\\/]/u)),b=Ei.join(s.staged,"specs",d.capability,"spec.md"),N=(await Ai({sourceRoot:h,source:v,targetRoot:t.nativeRoot,target:b,maxBytes:L$,label:`Native Archive proposed spec ${d.capability}`,expectedHash:p.proposedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("stage",d.source)}})).hash;if(N!==p.proposedHash)throw new Error(`Proposed Native spec changed after preflight: ${d.capability}`);c.push({id:`spec-${u+1}-${d.capability}`,type:"write",target:xi(t,f),staged:xi(t,b),...d.operation==="replace"?{backup:xi(t,m)}:{},expectedTargetHash:d.operation==="create"?null:d.base_hash,stagedHash:N})}let l=C(t,i.name);return c.push({id:"archive-change",type:"move",source:xi(t,l),target:xi(t,o),expectedSourceHash:await zh(l),expectedTargetHash:null}),{schema:"comet.native.transaction.v2",id:r,kind:"archive",status:"prepared",change:i.name,createdAt:n.toISOString(),preflightHash:a.preflightHash,operations:c}}function Xh(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Ei.resolve(e.nativeRoot,...i.target.split("/"))}async function tS(e,t,i){let n=await vn(e,t.id);if(n.some(h=>h.type==="archive-finalized"))return;let r=n.some(h=>h.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let h=t.operations.find(b=>b.id==="archive-change");if(!h||h.type!=="move"||!h.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await Qt(Xh(e,t));if(v?.kind!=="directory"||v.hash!==h.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Xh(e,t),o=Ei.join(a,$e),s=await ty(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await ye(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let h=ms(ct,c,new Set,ua,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=vs(ct,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},ua,void 0)}let u=F(`archive:${t.id}:${s.name}`),d=await qe(a,l.trajectoryRef),f=d.filter(h=>h.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(f.length>1||f.some(h=>h.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let p=f.find(h=>h.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:u,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(p&&t.schema==="comet.native.transaction.v2"&&(!F$(p.data,m)||p.runId!==l.runId||p.timestamp!==t.createdAt||p!==d.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||f.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await Zl(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Lr(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await ey(o,h)}p||(p=await Hn({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await lr({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Zn(a,l),await eS(e,s.name),t.schema==="comet.native.transaction.v2"?await Zl(e,t,"archive-finalized"):await Lr(e,t,"archive-finalized")}async function iS(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await vn(e,t.id)).some(o=>o.type==="operation-started")){let o=await hr({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new va(o,"Native Archive facts changed before the first transaction operation")}let a=await Jb(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await W(e,t.change),c=await fr({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await tS(e,a,i),Zl(e,a,"commit")}let n=await Zg(e,t);return await tS(e,n,i),Lr(e,n,"commit")}function K$(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Ei.resolve(t.projectRoot)!==Ei.resolve(e.projectRoot)||Ei.resolve(t.nativeRoot)!==Ei.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function nS(e){return re(e.paths,`archive ${e.name}`,()=>He(e.paths,e.name,`archive ${e.name}`,async()=>{await St(e.paths,e.name);let t=await ci(e.paths,"archive",`archive ${e.name}`);try{if(!/^[a-f0-9]{64}$/u.test(e.expectedPreflightHash))throw new Error("Native Archive expected preflight must be a SHA-256 hash");let i=e.now??new Date,n=await hr({paths:e.paths,name:e.name,now:i});if(!n.ready||n.preflightHash!==e.expectedPreflightHash)throw new va(n);let r=await W(e.paths,e.name);B$(r),await V$(e.paths,r);let a=D$(),o=await U$({paths:e.paths,state:r,now:i,transactionId:a,preflight:n,hooks:e.hooks});return await qb(e.paths,o),await e.hooks?.afterPrepared?.(o),await iS(e.paths,o,e.hooks),{archiveDir:Xh(e.paths,o),transactionId:a,preflightHash:n.preflightHash}}finally{await li(t)}}))}async function rS(e){return re(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await ci(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await nt(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await Kh(e.paths,e.transactionId):i;return K$(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?iS(e.paths,n):n.schema==="comet.native.transaction.v2"?zb(e.paths,n):Wc(e.paths,n)}finally{await li(t)}},{allowedTransactionId:e.transactionId})}var G$=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function Y$(e){return e.phase==="shape"?["summary","shared-understanding-confirmation"]:e.phase==="build"?e.approval==="confirmed"?["summary","artifact-or-no-code-reason"]:["summary","artifact-or-no-code-reason","shared-understanding-confirmation"]:e.phase==="verify"?["summary","verification-result","verification-report"]:[]}function De(e){let i=(e.findings??[]).filter(l=>!Wr(l.code)),n=i.find(l=>l.requiresUserDecision),r=i.find(l=>l.repairCommand!==null||G$.test(l.code)),a=i.find(l=>l.code==="repair-iteration-limit"||l.code==="repair-override-exhausted"),o=i.find(l=>l.code==="repair-stagnation-stop"),s=[...new Set(i.map(l=>l.requiredAction))].sort();if(e.done)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"done",action:"none",command:null,requiresUserDecision:!1,requiredInputs:[]};if(a)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"]};if(n)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:s};if(o)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:null,requiresUserDecision:!1,requiredInputs:["new-repair-hypothesis"]};if(r)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:r.repairCommand,requiresUserDecision:!1,requiredInputs:s};if(e.evidenceRetreat)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"`,requiresUserDecision:!1,requiredInputs:["summary"]};if(e.state.phase==="build"&&e.state.verification_result==="fail")return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:["repair-verification-gaps"]};if(i.length>0)return e.state.phase==="archive"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:s}:s.includes("refresh-verification-receipts")?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:`comet native receipt refresh ${e.state.name} --apply`,requiresUserDecision:!1,requiredInputs:s}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:s};if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");return e.archiveConfirmation==="required"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"archive",command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"]}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"archive",command:`comet native archive ${e.state.name} --expect-preflight ${e.archivePreflightHash}`,requiresUserDecision:!1,requiredInputs:[]}}return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",command:e.archiveReady?`comet native archive ${e.state.name} --dry-run`:null,requiresUserDecision:!1,requiredInputs:e.archiveReady?[]:["archive-readiness"]}}let c=e.state.phase==="shape"||e.state.phase==="build"&&e.state.approval!=="confirmed"?" --confirmed":"";return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"${c}`,requiresUserDecision:!1,requiredInputs:Y$(e.state)}}import X$ from"path";var aS=10*1024*1024,j=class extends Error{},Qh=`Usage: comet native <command> [options]
199
+ `)}import YN from"node:path";var SO="comet.native.contract.v1",kO="comet.native.acceptance-set.v1",XN=/^[a-f0-9]{64}$/u,Go={maxAcceptanceCriteria:Ko.maxCriteria};function QN(e,t){let i=YN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||YN.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function ZN(e){return H("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
200
+ `))}function EO(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(XN))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(XN))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=QN(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:ZN(e.markdown)},markdown:e.markdown}}function RO(e,t){return eb(e.id,t.id)}function eb(e,t){return e<t?-1:e>t?1:0}function tb(e){let t=QN(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(EO).sort((d,f)=>eb(d.snapshot.capability,f.snapshot.capability)),n=i.map(({snapshot:d})=>d.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=zN(e.briefMarkdown,t,Go.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...WN(f,d.source,Go.maxAcceptanceCriteria-a.length)),a.push(...UN(f,d.source,Go.maxAcceptanceCriteria-a.length)));if(a.sort(RO),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Go.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Go.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:ZN(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=H(kO,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:H(SO,u)}}var Yt={maxSpecs:64,maxFileBytes:eo,maxTotalBytes:4*1024*1024};async function bt(e){if(e.specChanges.length>Yt.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await ge({root:e.changeDir,ref:e.briefRef,maxBytes:Yt.maxFileBytes}),i=t.size,n=[];for(let r of e.specChanges){if(r.operation==="remove"){n.push({capability:r.capability,operation:"remove",source:null,baseHash:r.base_hash,markdown:null});continue}if(!r.source)throw new Error(`Native contract ${r.capability} has no proposed spec source`);let a=await ge({root:e.changeDir,ref:r.source,maxBytes:Yt.maxFileBytes});if(i+=a.size,i>Yt.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");n.push({capability:r.capability,operation:r.operation,source:a.ref,baseHash:r.base_hash,markdown:a.text})}return{contract:tb({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as MO,spawn as Lh}from"node:child_process";import{createHash as FO}from"node:crypto";import{existsSync as yb}from"node:fs";import bi from"node:path";import{promisify as LO}from"node:util";import{spawn as CO}from"node:child_process";import Ah from"node:path";var PO=1e3,AO=2;async function ib(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Ah.win32.isAbsolute(i)?Ah.win32.resolve(i):"C:\\Windows",r=Ah.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=CO(r,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),PO)}catch{u(!1)}});for(let o=0;o<AO;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}import{randomUUID as TO}from"crypto";import{promises as _O}from"fs";import ha from"path";var Xt={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pa=/^[a-f0-9]{64}$/u;function Vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jl(e,t,i){let n=new Set(t),r=Object.keys(e).filter(o=>!n.has(o)),a=t.filter(o=>!(o in e));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Dn(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function nb(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xh(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rb(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||ha.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=ha.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Th(e,t){return ha.join(C(e,t),"runtime","checkpoints","progress.json")}function Ji(e,t){return ha.join(C(e,t),"runtime","checkpoint-journal.json")}function _h(e,t,i){if(!pa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return ha.join(C(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function Ih(e){if(!pa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function jh(e,t,i){let n=await ue({root:e,file:t,maxBytes:Xt.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function xO(e,t){let i=Vl(e,`checkpoint manifest artifact ${t}`);Jl(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=rb(Dn(i.path,`checkpoint artifact ${t} path`,4096)),r=ai(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!pa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:xh(i.size,`checkpoint artifact ${t} size`)}}function zl(e,t){let i=Vl(e,"Native checkpoint manifest");if(Jl(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Xt.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(xO),r=[...n].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(n)!==JSON.stringify(r))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(n.map(o=>o.path)).size!==n.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=xh(i.totalBytes,"checkpoint manifest totalBytes");if(n.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Xt.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:n,totalBytes:a}}function Yo(e){return F(JSON.stringify(zl(e,e.change)))}function Oh(e,t){let i=Vl(e,"Native progress checkpoint");if(Jl(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let n=i.phase;if(n!=="shape"&&n!=="build"&&n!=="verify"&&n!=="archive")throw new Error("Native checkpoint phase is invalid");let r=nb(i.previousRevision,"Native checkpoint previousRevision"),a=nb(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Dn(i.manifestHash,"Native checkpoint manifestHash",64);if(!pa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=Ih(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Dn(i.inputHash,"Native checkpoint inputHash",64);if(!pa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Dn(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=xh(i.artifactCount,"Native checkpoint artifactCount");if(u>Xt.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Dn(i.summary,"Native checkpoint summary"),f=Dn(i.nextAction,"Native checkpoint nextAction");if(Ne(d)!==d||Ne(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Dn(i.id,"Native checkpoint id",128),change:t,phase:n,previousRevision:r,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function ab(e,t){let i=Vl(e,"Native checkpoint journal");if(Jl(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let n=_t(i.previousState),r=_t(i.nextState),a=Oh(i.checkpoint,t),o=zl(i.manifest,t),s=Dn(i.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(n.name!==t||r.name!==t||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==Yo(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function ob(e,t,i){let n=ha.resolve(e.projectRoot,...t.split("/"));if(!$(e.projectRoot,n)||$(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=Za(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ue({root:e.projectRoot,file:n,maxBytes:Xt.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function sb(e,t,i,n){let r=i.map(rb).sort();if(r.length>Xt.maxArtifacts)throw new Error(`Checkpoint supports at most ${Xt.maxArtifacts} artifacts`);if(new Set(r).size!==r.length)throw new Error("Checkpoint artifacts must not contain duplicates");let a=[],o=0;for(let s of r){let c=await ob(e,s,n);if(o+=c.size,o>Xt.maxTotalBytes)throw new Error("Checkpoint artifacts exceed the total byte budget");a.push(c)}return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:a,totalBytes:o}}async function $h(e,t){let i=Th(e,t);await A(e.nativeRoot,i);try{return Oh(await jh(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Hh(e,t,i){let n=_h(e,t,i);await A(e.nativeRoot,n);let r=await jh(e.nativeRoot,n,"Native checkpoint manifest"),a=zl(r,t);if(Mh(e,a),Yo(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function zi(e,t){let i=Ji(e,t);await A(e.nativeRoot,i);try{let n=ab(await jh(e.nativeRoot,i,"Native checkpoint journal"),t);return Mh(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Dh(e,t,i,n){let r=zl(i,t);Mh(e,r);let a=Yo(r),o=_h(e,t,a);await A(e.nativeRoot,o);try{let s=await Hh(e,t,a);if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Native checkpoint manifest hash collision")}catch(s){if(s.code!=="ENOENT")throw s}return await de(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Mh(e,t){for(let i of t.artifacts){let n=Za(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function cb(e,t){let i=Oh(t,t.change),n=await Hh(e,i.change,i.manifestHash),r=F(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:n.artifacts}));if(i.inputHash!==r||i.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Th(e,t.change);await A(e.nativeRoot,a),await de(a,i,{containedRoot:e.nativeRoot})}async function lb(e,t){let i=ab(t,t.change),n=Ji(e,t.change);if(await A(e.nativeRoot,n),await zi(e,t.change))throw new Error(`Native checkpoint recovery is already pending for ${t.change}`);await de(n,i,{containedRoot:e.nativeRoot})}async function ub(e){let t;try{t=await $h(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Th(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],n=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let r=null;try{r=await Hh(e.paths,e.name,t.manifestHash);let a=F(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:r.artifacts}));if(t.inputHash!==a||t.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of r.artifacts)try{let s=await ob(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),n.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:_h(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function db(e){let t=(e.now??new Date).toISOString(),i=e.checkpointId?.()??TO(),n={...e.checkpoint,id:i,createdAt:t},r={schema:"comet.native.checkpoint-journal.v1",id:i,change:e.previousState.name,inputHash:n.inputHash,createdAt:t,previousState:e.previousState,nextState:e.nextState,checkpoint:n,manifest:e.manifest};return await Dh(e.paths,e.previousState.name,e.manifest),await lb(e.paths,r),r}async function Xo(e,t,i){let n=await zi(e,t);if(!n)return null;if(await Dh(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Gr(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await cb(e,n.checkpoint),await i?.afterProgressWritten?.(n),await _O.rm(Ji(e,t),{force:!0}),n}async function fb(e,t,i){return re(e,`continue checkpoint ${t}`,()=>He(e,t,`continue checkpoint ${t}`,async()=>(await Ni(e,t),Xo(e,t,i))))}async function St(e,t){await Ni(e,t),await Xo(e,t)}import{constants as Fh,promises as Ot}from"node:fs";import ur from"node:path";var IO=/^[a-f0-9]{64}$/u,jO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,dr=512*1024;function OO(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wl(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return ze(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function $O(e,t){let i=ur.resolve(e),n=ur.resolve(t);if(!$(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...ur.relative(i,n).split(ur.sep).filter(Boolean)]){o&&(a=ur.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return r}async function hb(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!OO(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function pb(e){if(!IO.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function HO(e){let t=jO.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function mb(e,t,i){return ur.join(C(e,t),...pb(i).split("/"))}async function DO(e,t,i){let n=await $O(i,ur.dirname(e)),r=await Ot.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>dr)throw new Error(`Native check receipt exceeds ${dr} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!$(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Fh.O_RDONLY|Fh.O_NOFOLLOW|Fh.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await hb(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Wl(r,l)||!Wl(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let E=dr+1-p,N=await c.read(m,0,Math.min(m.length,E),null);if(N.bytesRead===0)break;if(p+=N.bytesRead,p>dr)throw new Error(`Native check receipt exceeds ${dr} bytes`);f.push(Buffer.from(m.subarray(0,N.bytesRead)))}let[h,v,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await hb(n),!v.isFile()||v.isSymbolicLink()||b!==o||!$(a,b)||!Wl(l,h)||!Wl(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Ul(e,t,i){let n=HO(i),r=C(e,t),a=mb(e,t,n);await A(e.nativeRoot,a);let o=Li(await DO(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}async function vb(e){let t=Li(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let i=pb(t.receiptHash),n=mb(e.paths,e.name,t.receiptHash);if(Buffer.byteLength(JSON.stringify(t,null,2)+`
201
+ `,"utf8")>dr)throw new Error(`Native check receipt exceeds ${dr} bytes`);await A(e.paths.nativeRoot,n);try{let o=await Ul(e.paths,e.name,i);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return i}catch(o){if(o.code!=="ENOENT")throw o}await de(n,t,{containedRoot:e.paths.nativeRoot});let a=await Ul(e.paths,e.name,i);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return i}var qh=64*1024,qO=12e4,Qo=3600*1e3,BO=4e3,VO="native-runtime:manual-evidence",gb=LO(MO),JO=new Set([".bat",".cmd",".ps1"]),zO=["$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("; ");function WO(e){let t=(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function UO(e,t,i){let r=bi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(t.PATH??"").split(bi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=bi.win32.extname(e)?[e]:WO(t).map(s=>`${e}${s}`);return r.flatMap(s=>o.map(c=>s?bi.join(s,c):bi.resolve(i,c)))}function KO(e,t,i){return UO(e,t,i).find(n=>yb(n))??e}function GO(e){let t=e.SYSTEMROOT??e.SystemRoot;if(t){let i=bi.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(yb(i))return i}return"powershell.exe"}function YO(e,t,i){let n=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),r=Buffer.from(zO,"utf16le").toString("base64");return Lh(GO(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function XO(e,t,i){if(process.platform!=="win32")return Lh(e,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=KO(e,i.env,i.cwd);return JO.has(bi.win32.extname(n).toLowerCase())?YO(n,t,i):Lh(n,[...t],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function Nb(e){return re(e.paths,e.operation,()=>He(e.paths,e.name,e.operation,async()=>(await St(e.paths,e.name),e.issue(await W(e.paths,e.name)))))}function QO(e,t){let i=e.trim();if(!i||Buffer.byteLength(i,"utf8")>qh)throw new Error(`${t} is invalid`);return i}function bb(e,t){let i=[...e].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!t.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Zo(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([gi(e,t.name,t.implementation_scope),bt({changeDir:C(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=t.run_id?`run:${t.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:Rl(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var ZO=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Kl(e,t){let i=[];for(let n of ZO){let r=e.bindings[n],a=t[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function Sb(e){let t=await Zo(e.paths,e.state),i=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),n=e.checkReceipt.status==="passed"?"passed":i?"blocked":"failed",r=El({kind:"static-inspection",role:"required-check",status:n,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:t.scope.scope.changes.map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:n==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await xl({paths:e.paths,name:e.state.name,receipt:r});return{receipt:r,ref:a}}async function Gl(e){return Nb({paths:e.paths,name:e.name,operation:`issue manual receipt ${e.name}`,issue:t=>e$({...e,state:t})})}async function e$(e){let t=await Zo(e.paths,e.state),i=El({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:t.bindings,acceptanceIds:bb(e.acceptanceIds,t.acceptanceIds),actor:VO,issuedAt:(e.now??new Date).toISOString(),evidence:{steps:[...e.steps],observations:[...e.observations]}});return{receipt:i,ref:await xl({paths:e.paths,name:e.state.name,receipt:i})}}function t$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function i$(e){let t=t$(e.context.scope.baseline),i=await bn(e.paths,t,{origin:"explicit",now:e.now}),n=Tn({baseline:t,current:i,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths});return{snapshotHash:n.scope.currentProjectionHash,scopeHash:n.scope.scopeHash,matched:n.scope.currentProjectionHash===e.context.bindings.snapshotHash&&n.scope.scopeHash===e.context.bindings.scopeHash}}async function wb(e){try{let[{stdout:t},{stdout:i}]=await Promise.all([gb("git",["-C",e,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),gb("git",["-C",e,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=bi.resolve(t.trim()),r=bi.relative(e,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||bi.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function kb(e){return Nb({paths:e.paths,name:e.name,operation:`issue automated receipt ${e.name}`,issue:t=>n$({...e,state:t})})}async function n$(e){let t=await Zo(e.paths,e.state),i=await wb(e.paths.projectRoot),n=(e.now?.()??new Date).toISOString(),r=e.timeoutMs??qO;if(!Number.isSafeInteger(r)||r<1||r>Qo)throw new Error(`Native automated command timeout must be an integer from 1 through ${Qo}`);let a=[],o=0,s=0,c=FO("sha256"),l=!1,u=XO(e.command,e.args,{cwd:e.paths.projectRoot,env:{...process.env}}),d=w=>{if(c.update(w),s+=w.byteLength,o>=qh)return;let y=qh-o,g=w.subarray(0,y);a.push(Buffer.from(g)),o+=g.byteLength};u.stdout.on("data",d),u.stderr.on("data",d);let f=await new Promise((w,y)=>{let g=!1,k=null,x=null,U=z=>{g||(g=!0,clearTimeout(D),x&&clearTimeout(x),w(z))},D=setTimeout(()=>{l=!0,k=ib(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),x=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),U({exitCode:124,signal:"SIGKILL"})},BO)},r);u.once("error",z=>{if(l){(k??Promise.resolve()).then(()=>U({exitCode:124,signal:"SIGKILL"}));return}g||(g=!0,clearTimeout(D),x&&clearTimeout(x),y(z))}),u.once("close",(z,ne)=>{(k??Promise.resolve()).then(()=>U({exitCode:l?124:z??1,signal:ne??(l?"SIGKILL":null)}))})}),p=(e.now?.()??new Date).toISOString(),[m,h]=await Promise.all([wb(e.paths.projectRoot),i$({paths:e.paths,context:t,now:e.now?.()})]),v=t.scope.current.capture,E=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,N=l||!h.matched||!E?"blocked":f.exitCode===0?"passed":"failed",S=Buffer.concat(a,o).toString("utf8").trim(),R=El({kind:"automated-check",role:"acceptance-evidence",status:N,bindings:t.bindings,acceptanceIds:bb(e.acceptanceIds,t.acceptanceIds),actor:`native-runtime:command:${e.command}`,issuedAt:p,evidence:{executable:e.command,args:[...e.args],cwd:".",exitCode:f.exitCode,signal:f.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:p,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{...h,matched:h.matched&&E},outputHash:c.digest("hex"),outputSummary:QO(Ne(S||`(exit ${f.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:R,ref:await xl({paths:e.paths,name:e.state.name,receipt:R})}}async function Eb(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Ul(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Wi=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function r$(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}function a$(e){let t=Rb.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/");if(!t||t===".."||t.startsWith("../")||Rb.posix.isAbsolute(t))throw new Error("Native root is outside the project root");return t}async function o$(e){let t=r$(e.bundle.baseline),i=await bn(e.paths,t,{origin:"explicit",now:e.now});return Tn({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function Vh(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await gi(e.paths,e.state.name,e.state.implementation_scope),i=await bt({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await o$({paths:e.paths,bundle:t,now:e.now}),r=[];return i.contract.contractHash!==t.scope.contractHash&&r.push("verification-contract-stale"),n!==t.scope.currentProjectionHash&&r.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:r}}async function es(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Vh(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function Pb(e){let t=await ge({root:C(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:ql(t.text)}}function s$(e){let{receipt:t,implementationScope:i}=e,n=[],r=i.scope.changes.filter(o=>o.after!==null),a=r.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==r.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==r.length||t.counts.bytesScanned!==a))&&n.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&n.push("verification-receipt-outcome-mismatch"),n}function c$(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Rl(e.implementationScope.scope.declaredArtifacts)}}async function Cb(e){let t=await oa(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=Kl(t,e.expectedBindings);if(i.push(...n.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Wi([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let r=await Eb({paths:e.paths,state:e.state,receipt:t});if(r){let a=s$({receipt:r,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function Ab(e){let t=c$({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await Cb({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Wi)return i.push(...a.details),null;throw a});if(r!==null&&r.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let n of e.trace.entries)if(n.status!=="missing")for(let r of n.evidenceRefs){let a=await Cb({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Wi)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(n.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Wi(i)}async function xb(e){if(e.state.phase!=="verify")throw new Error(`Native verification evidence requires Verify, got ${e.state.phase}`);let t=await Vh(e);if(t.findingCodes.length>0)return{ready:!1,findingCodes:t.findingCodes,envelope:null,evidenceRef:null,reportSnapshot:null};let i=await Pb(e);if(e.result==="pass"&&!e.receiptRef)throw new Error("Native passing verification requires a typed required-check receipt");let n=e.receiptRef?[e.receiptRef]:[],r=My(t.contract.acceptance,i.entries,{nativeRootRef:a$(e.paths),allowMissing:e.result==="fail"});if(e.result==="pass"&&r.entries.some(c=>c.status==="failed"||c.status==="missing"))throw new Error("Native passing verification cannot include failed or missing acceptance criteria");try{await Ab({paths:e.paths,state:e.state,result:e.result,trace:r,requiredReceiptRefs:n,contractHash:t.contractHash,implementationScope:t.bundle})}catch(c){if(c instanceof Wi)return{ready:!1,findingCodes:["verification-receipt-binding-mismatch"],envelope:null,evidenceRef:null,reportSnapshot:null,...c.details.length>0?{receiptBindingFailures:c.details}:{}};throw c}let a=e.state.partial_allowance?await lh(e.paths,e.state.name,e.state.partial_allowance):null,o=Ly({change:e.state.name,sourceRevision:e.state.revision,result:e.result,contractHash:t.contractHash,acceptanceHash:t.acceptanceHash,implementationScope:{ref:e.state.implementation_scope,bundle:t.bundle},reportRef:i.ref,reportHash:i.hash,requiredReceiptRefs:n,acceptanceTrace:r,partialAllowance:e.state.partial_allowance&&a?{ref:e.state.partial_allowance,allowance:a}:null,now:e.now}),s=wt("verifications",o.envelopeHash);return{ready:!0,findingCodes:[],envelope:o,evidenceRef:s,reportSnapshot:{hash:i.hash,text:i.text}}}async function Tb(e){if(!e.preparation.ready||e.preparation.envelope===null||e.preparation.evidenceRef===null||e.preparation.reportSnapshot===null)throw new Error("Native verification evidence is not ready to persist");if(await oN({paths:e.paths,name:e.state.name,...e.preparation.reportSnapshot}),await hN({paths:e.paths,name:e.state.name,evidence:e.preparation.envelope})!==e.preparation.evidenceRef)throw new Error("Native verification evidence persistence ref changed")}function Bh(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function fr(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Bh(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Vh(e),On(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Bh(e.state.verification_result,"stale"),envelope:null};let n=await Pb({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),r=[...t.findingCodes];(n.hash!==i.reportHash||n.ref!==i.reportRef)&&r.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&r.push("verification-state-mismatch");try{await Ab({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{r.push("verification-receipt-invalid")}let a=[...new Set(r)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Bh(e.state.verification_result,"invalid"),envelope:null}}}function u$(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Ib(e){try{return await l$.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function d$(e,t){try{return(await ge({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function f$(e,t,i){let n=Jt(e,i.capability);if(!$(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=_b.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await d$(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await ge({root:C(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function h$(e,t){return Ib(Be(e,t))}async function hr(e){let t=e.now??new Date,i=await W(e.paths,e.name),n=await le(e.paths.projectRoot),r=u$(i.name,t),a=_b.resolve(e.paths.nativeRoot,...r.split("/"));if(!$(e.paths.nativeRoot,a))throw new Error("Native archive target escapes its root");let[o,s,c,l,u,d,f]=await Promise.all([Promise.all(i.spec_changes.map(p=>f$(e.paths,i.name,p))),fr({paths:e.paths,state:i,now:t}),Tl(e.paths,i.name),tr(e.paths,i.name),Kr(e.paths,i.name),h$(e.paths,i.name),Ib(a)]);return uy({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:l||u||d,targetRef:r,targetExists:f,specs:o,evidence:s.evidence,findingCodes:[...s.findingCodes,...c.findingCodes]})}import{promises as Jh}from"node:fs";import Ui from"node:path";var p$="comet.native.archive-tree.v1",m$={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function $b(e){let t={...m$,...e};for(let[i,n]of Object.entries(t))if(!Number.isSafeInteger(n)||n<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function jb(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Ob(e,t,i,n){if(i.entryCount+=1,i.entryCount>n.maxEntries)throw new Error(`Native Archive content exceeds ${n.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>n.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${n.maxRefBytes} bytes: ${t.ref}`);let r=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=r+(e.length===0?0:1),i.manifestBytes+2>n.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${n.maxManifestBytes} bytes`);e.push(t)}async function Hb(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await pt({root:e,directory:t,label:`Native Archive content directory ${Ui.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=jb(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Ui.join(t,u.name),f=Ui.relative(e,d).replaceAll("\\","/"),p=await Jh.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){Ob(i,{ref:f,kind:"directory"},n,r),await Hb(e,d,i,n,r,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await ue({root:e,file:d,maxBytes:r.maxFileBytes,label:`Native Archive content file ${f}`});if(n.totalBytes+=m.size,n.totalBytes>r.maxTotalBytes)throw new Error(`Native Archive content exceeds ${r.maxTotalBytes} total file bytes`);Ob(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await pt({root:e,directory:t,label:`Native Archive content directory ${Ui.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(jb(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Ui.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function zh(e,t={}){let i=$b(t);e=Ui.resolve(e);let n=await Jh.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await Hb(e,e,r,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(r);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return F(`${p$}\0${o}`)}async function Qt(e,t={}){let i=$b(t);e=Ui.resolve(e);let n;try{n=await Jh.lstat(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(n.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(n.isFile())return{kind:"file",hash:(await ue({root:Ui.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Ui.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await zh(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as Je}from"node:fs";import be from"node:path";var Uh=16*1024*1024,v$=256*1024,g$=16*1024,ts="comet.native.archive-cas.v1";function w$(e,t){let i=be.resolve(e.nativeRoot,...t.split("/"));if(be.relative(e.nativeRoot,i).split(be.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function Ve(e,t){return A(e.nativeRoot,w$(e,t))}function Mn(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function ma(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function lt(e){let t=await Qt(e.target);if(!Mn(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ma(t)}`);return t}async function qb(e,t){let i=go(t),n=await Pt(e,i.id);await Je.mkdir(n.staged,{recursive:!0}),await Je.mkdir(n.backups,{recursive:!0}),await de(n.journal,i,{containedRoot:e.nativeRoot}),await mt(e,i.id,"prepared")}async function Kh(e,t){let i=await Pt(e,t),n=await ue({root:e.nativeRoot,file:i.journal,maxBytes:v$,label:`Native Archive transaction journal ${t}`}),r=go(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function Yl(e,t,i){let n=go({...t,status:i}),r=await Pt(e,n.id);return await de(r.journal,n,{containedRoot:e.nativeRoot}),n}function Xl(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Db(e){return{...Xl(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Fn(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function y$(e,t){return Fn(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ce(e){try{return await Je.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Si(e){let t=await Je.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=Db(t),n=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:Uh,label:e.label}),r=await Je.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!y$(i,Db(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Xl(r),size:n.size}}function N$(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let r=e;if(Object.keys(r).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=r.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(r.schema!==ts||r.operationId!==t.id||r.role!==i||r.hash!==n)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ts,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function ki(e,t,i,n){let r=await Pt(e,t.id),a=be.join(r.backups,".cas"),o=`.${be.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:be.join(a,`${i.id}.original.json`),postRecord:be.join(a,`${i.id}.post.json`),candidate:be.join(a,`${i.id}.candidate`),originalQuarantine:be.join(be.dirname(n),`${o}.original`),rollbackQuarantine:be.join(be.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>A(e.nativeRoot,c))),s}async function $t(e){if(!await ce(e.file))return null;let t=await ue({root:e.paths.nativeRoot,file:e.file,maxBytes:g$,label:`Archive CAS ${e.operation.id} ${e.role} record`});return N$(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Ql(e){let t=await $t(e);if(t){if(!Fn(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await di({root:e.paths.nativeRoot,directory:be.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ts,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await de(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await $t(e);if(!n||!Fn(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function Ae(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Fn(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function b$(e){let t=await Si({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Ql({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Ae({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function S$(e){if(!await ce(e.quarantine)||await ce(e.target))return;let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await Je.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([Je.lstat(e.quarantine),Je.lstat(e.target)]);if(!Fn(Xl(i),Xl(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await Je.unlink(e.quarantine),await t.verify()}async function Bb(e){if(await ce(e.quarantine)){await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Ae({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Ae({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await Je.rename(e.target,e.quarantine),await t.verify(),await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await S$(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function pr(e){if(!await ce(e.file))return;await Ae(e);let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.file),label:e.label});await t.verify(),await Ae(e),await Je.unlink(e.file),await t.verify()}async function Mb(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await Ve(e,t.target),r=await Ve(e,t.backup),a=await Qt(r);if(a!==null){if(!Mn(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await lt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ai({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:Uh,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await lt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function Vb(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await ki(e.paths,e.journal,e.operation,e.target),n=await $t({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ce(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Ae({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await Mb(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await ce(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await b$({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Ae({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await Mb(e.paths,e.operation,e.hooks),await Bb({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:n,hooks:e.hooks}),{record:n,quarantine:i.originalQuarantine}}async function Fb(e){let t=await ki(e.paths,e.journal,e.operation,e.target);return await ce(t.candidate)?(await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await di({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ai({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:Uh,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function k$(e){let t=e.operation.stagedHash,i=await ki(e.paths,e.journal,e.operation,e.target),n=await $t({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await ce(e.target))return await Ae({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await ce(i.candidate)&&await pr({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await ce(e.target)){let c=await Fb(e),l=await Si({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fn(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await Ql({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await pr({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await Fb(e),a=await Si({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await di({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Ae({paths:e.paths,file:r,operation:e.operation,record:{schema:ts,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await Je.link(r,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Si({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Fn(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await Ql({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await pr({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function E$(e,t,i,n){let r=await Ve(e,i.target),a=await Ve(e,i.staged);if(await lt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await ki(e,t,i,r);(!await $t({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ce(r))&&await Vb({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await Qt(r);if(o!==null&&!Mn(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${ma(o)}`)}await k$({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await lt({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function R$(e,t,i,n){let r=await Ve(e,i.target);await Vb({paths:e,journal:t,operation:i,target:r,hooks:n}),await lt({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function C$(e,t){let i=await Ve(e,t.source),n=await Ve(e,t.target),[r,a]=await Promise.all([Qt(i),Qt(n)]);if(!(r===null&&Mn(a,t.expectedSourceHash,"directory"))){if(!Mn(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ma(r)}, target=${ma(a)}`);await Je.mkdir(be.dirname(n),{recursive:!0}),await Je.rename(i,n),await lt({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function P$(e,t,i,n){return i.type==="write"?E$(e,t,i,n):i.type==="remove"?R$(e,t,i,n):C$(e,i)}function A$(e){let t=0,i=!1,n=[];for(let r of e.events){if(r.type!=="operation-started"&&r.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||r.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(r.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);n.push(a.id),t+=1,i=!1}return n}async function x$(e,t,i,n){let r=await Ve(e,i.target);if(i.type==="write"){let a=await Ve(e,i.staged);await lt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await ki(e,t,i,r),s=await $t({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Ae({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await lt({target:await Ve(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await $t({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ce(o.originalQuarantine))await Ae({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await lt({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await lt({target:await Ve(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await ki(e,t,i,r),o=await $t({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ce(a.originalQuarantine))await Ae({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!n)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}n||(await lt({target:await Ve(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await lt({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Jb(e,t,i){let n=t.status==="prepared"?await Yl(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await vn(e,n.id),a=A$({journal:n,events:r}),o=new Set(a),s=r.some(l=>l.type==="archive-finalization-started");for(let l of n.operations.slice(0,a.length))await x$(e,n,l,s);let c=o.size;for(let l of n.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await mt(e,n.id,"operation-started",l.id),await P$(e,n,l,i),await mt(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await Kh(e,n.id),n}async function T$(e){try{return await Ae(e),!0}catch{return!1}}async function _$(e){await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await ui({root:e.paths.nativeRoot,directory:be.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Ae({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await Je.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Ae({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Wh(e){if(e.operation.type!=="write")return;let t=await ki(e.paths,e.journal,e.operation,e.target);if(!await ce(t.candidate))return;let i=await Si({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await pr({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ts,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function I$(e,t,i,n){let r=await Ve(e,i.target),a=await ki(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await $t({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await $t({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ce(a.candidate)&&await ce(r)){let l=await Si({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Si({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Fn(l.identity,u.identity)&&(c=await Ql({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ce(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Ae({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ce(r)&&!(s!==null&&await T$({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Qt(r);if(Mn(u,o)){await Wh({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await Bb({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await ce(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ce(r)){if(!s||!await ce(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await _$({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await ce(a.originalQuarantine)&&await pr({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ce(a.rollbackQuarantine)&&await pr({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Wh({paths:e,journal:t,operation:i,target:r}),await lt({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function j$(e,t){let i=await Ve(e,t.source),n=await Ve(e,t.target),[r,a]=await Promise.all([Qt(i),Qt(n)]);if(!(Mn(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!Mn(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ma(r)}, target=${ma(a)}`);await Je.mkdir(be.dirname(i),{recursive:!0}),await Je.rename(n,i)}}async function zb(e,t,i){let n=await vn(e,t.id);if(n.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Yl(e,t,"rolling-back");await mt(e,r.id,"rollback-started");let a=new Set(n.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...r.operations].reverse())a.has(o.id)&&(o.type==="move"?await j$(e,o):await I$(e,r,o,i));return await mt(e,r.id,"rollback-completed"),r=await Yl(e,r,"rolled-back"),r}async function Lb(e,t,i){let n=await Ve(e,i.target);if(i.type==="write"){let r=await ki(e,t,i,n),a=await $t({paths:e,file:r.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Ae({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await lt({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function O$(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await Ve(e,i.target),r=await ki(e,t,i,n);if(await ce(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await Lb(e,t,i),i.expectedTargetHash!==null){let a=await $t({paths:e,file:r.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ce(r.originalQuarantine)&&await pr({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Wh({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await Lb(e,t,i)}async function Zl(e,t,i){return i==="commit"&&await O$(e,t),await mt(e,t.id,i),i==="commit"?Yl(e,t,"committed"):t}import{randomUUID as $$}from"crypto";import{promises as is}from"fs";import Ub from"path";var Gh="comet.selection.v2",H$=16*1024;function ns(e){return Ub.join(e,".comet","current-change.json")}function D$(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wb(e){return e===null||typeof e=="string"}function Kb(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!D$(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Wb(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Gh,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Gh)throw new Error(`current change selection schema must be ${Gh}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Wb(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Yh(e){let t;try{let n=ns(e),{bytes:r}=await un(n,H$,{label:"current change selection"});t=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",...Kb(t)}}async function Gb(e,t){let i=Kb(JSON.stringify(t));if(i.legacy)throw new Error("cannot write a legacy current change selection");let n=ns(e),r=`${n}.${$$()}.tmp`;await is.mkdir(Ub.dirname(n),{recursive:!0});try{await is.writeFile(r,`${JSON.stringify(i.selection,null,2)}
202
+ `,"utf8"),await is.rename(r,n)}catch(a){throw await is.rm(r,{force:!0}),a}}async function Yb(e){await is.rm(ns(e),{force:!0})}async function Xb(e,t,i){let n=await Yh(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await Yb(e),!0)}var lJ=16*1024;async function rs(e){let t=await Yh(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Vt(t.selection.change),t.selection)}function Qb(e){return ns(e.projectRoot)}async function eu(e,t){return re(e,`select change ${t}`,async()=>{Vt(t),await W(e,t),await Gb(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Zb(e){let t=await rs(e);return t?(await W(e,t.change),t.change):null}async function eS(e,t){return await $r(e.projectRoot),Xb(e.projectRoot,"native",t)}var q$=16*1024*1024,as=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"},va=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"};async function B$(e){try{return await rt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function V$(e){if(e.phase!=="archive")throw new Error(`Native change ${e.name} is not in Archive`);if(e.verification_result!=="pass")throw new Error(`Native change ${e.name} has not passed verification`);if(!e.verification_report)throw new Error(`Native change ${e.name} has no verification report`);if(e.archived)throw new Error(`Native change ${e.name} is already archived`)}async function J$(e,t){let i=C(e,t.name),n=await ir(i,t.brief),r=await Yr(i,t.verification_report),a=[...n.findings,...r.findings];if(a.length>0)throw new Error(`Native archive artifacts are invalid: ${a[0].message}`)}async function z$(e,t){let i=Jt(e,t.capability);await A(e.nativeRoot,i);let n=await B$(i),r=t.operation==="create"?null:t.base_hash;if(n!==r)throw new as(t.capability,r,n,i)}function W$(e,t,i){return Ei.join(e.archiveDir,`${i.toISOString().slice(0,10)}-${t}`)}async function U$(e){try{return await F$.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function K$(e){let{paths:t,state:i,now:n,transactionId:r,preflight:a}=e,o=W$(t,i.name,n);if(await U$(o))throw new Error(`Native archive target already exists: ${o}`);if(xi(t,o)!==a.targetRef)throw new Error("Native Archive target changed after preflight");let s=await Pt(t,r),c=[];for(let[u,d]of i.spec_changes.entries()){await z$(t,d);let f=Jt(t,d.capability),p=a.operations.find(S=>S.capability===d.capability&&S.operation===d.operation);if(!p)throw new Error(`Native Archive preflight has no operation for ${d.capability}`);if(d.operation!=="remove"&&p.proposedHash===null)throw new Error(`Native Archive preflight has no proposed hash for ${d.capability}`);let m=Ei.join(s.backups,"specs",d.capability,"spec.md");if(d.operation==="remove"){c.push({id:`spec-${u+1}-${d.capability}`,type:"remove",target:xi(t,f),backup:xi(t,m),expectedTargetHash:d.base_hash});continue}let h=C(t,i.name);await sy(h,d.source);let v=Ei.resolve(h,...d.source.split(/[\\/]/u)),b=Ei.join(s.staged,"specs",d.capability,"spec.md"),N=(await Ai({sourceRoot:h,source:v,targetRoot:t.nativeRoot,target:b,maxBytes:q$,label:`Native Archive proposed spec ${d.capability}`,expectedHash:p.proposedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("stage",d.source)}})).hash;if(N!==p.proposedHash)throw new Error(`Proposed Native spec changed after preflight: ${d.capability}`);c.push({id:`spec-${u+1}-${d.capability}`,type:"write",target:xi(t,f),staged:xi(t,b),...d.operation==="replace"?{backup:xi(t,m)}:{},expectedTargetHash:d.operation==="create"?null:d.base_hash,stagedHash:N})}let l=C(t,i.name);return c.push({id:"archive-change",type:"move",source:xi(t,l),target:xi(t,o),expectedSourceHash:await zh(l),expectedTargetHash:null}),{schema:"comet.native.transaction.v2",id:r,kind:"archive",status:"prepared",change:i.name,createdAt:n.toISOString(),preflightHash:a.preflightHash,operations:c}}function Xh(e,t){let i=t.operations.find(n=>n.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Ei.resolve(e.nativeRoot,...i.target.split("/"))}async function tS(e,t,i){let n=await vn(e,t.id);if(n.some(h=>h.type==="archive-finalized"))return;let r=n.some(h=>h.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!r){let h=t.operations.find(b=>b.id==="archive-change");if(!h||h.type!=="move"||!h.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let v=await Qt(Xh(e,t));if(v?.kind!=="directory"||v.hash!==h.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Xh(e,t),o=Ei.join(a,$e),s=await ty(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await ye(a);if(!c||c.runId!==s.run_id||c.currentStep!=="archive"&&!(c.currentStep===null&&c.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let l=c;if(c.currentStep==="archive"){let h=ms(ct,c,new Set,ua,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=vs(ct,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},ua,void 0)}let u=F(`archive:${t.id}:${s.name}`),d=await qe(a,l.trajectoryRef),f=d.filter(h=>h.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(f.length>1||f.some(h=>h.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let p=f.find(h=>h.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:u,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(p&&t.schema==="comet.native.transaction.v2"&&(!L$(p.data,m)||p.runId!==l.runId||p.timestamp!==t.createdAt||p!==d.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!r&&(s.archived||c.currentStep===null||f.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(r||(t.schema==="comet.native.transaction.v2"?(await Zl(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Lr(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await ey(o,h)}p||(p=await Hn({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await lr({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Zn(a,l),await eS(e,s.name),t.schema==="comet.native.transaction.v2"?await Zl(e,t,"archive-finalized"):await Lr(e,t,"archive-finalized")}async function iS(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await vn(e,t.id)).some(o=>o.type==="operation-started")){let o=await hr({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new va(o,"Native Archive facts changed before the first transaction operation")}let a=await Jb(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await W(e,t.change),c=await fr({paths:e,state:s,now:new Date(t.createdAt)});if(s.phase!=="archive"||s.archived||s.verification_result!=="pass"||!["complete","partial"].includes(c.freshness)||c.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${c.findingCodes.join(", ")||c.freshness}`)}});return await tS(e,a,i),Zl(e,a,"commit")}let n=await Zg(e,t);return await tS(e,n,i),Lr(e,n,"commit")}function G$(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Ei.resolve(t.projectRoot)!==Ei.resolve(e.projectRoot)||Ei.resolve(t.nativeRoot)!==Ei.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function nS(e){return re(e.paths,`archive ${e.name}`,()=>He(e.paths,e.name,`archive ${e.name}`,async()=>{await St(e.paths,e.name);let t=await ci(e.paths,"archive",`archive ${e.name}`);try{if(!/^[a-f0-9]{64}$/u.test(e.expectedPreflightHash))throw new Error("Native Archive expected preflight must be a SHA-256 hash");let i=e.now??new Date,n=await hr({paths:e.paths,name:e.name,now:i});if(!n.ready||n.preflightHash!==e.expectedPreflightHash)throw new va(n);let r=await W(e.paths,e.name);V$(r),await J$(e.paths,r);let a=M$(),o=await K$({paths:e.paths,state:r,now:i,transactionId:a,preflight:n,hooks:e.hooks});return await qb(e.paths,o),await e.hooks?.afterPrepared?.(o),await iS(e.paths,o,e.hooks),{archiveDir:Xh(e.paths,o),transactionId:a,preflightHash:n.preflightHash}}finally{await li(t)}}))}async function rS(e){return re(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await ci(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await nt(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await Kh(e.paths,e.transactionId):i;return G$(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?iS(e.paths,n):n.schema==="comet.native.transaction.v2"?zb(e.paths,n):Wc(e.paths,n)}finally{await li(t)}},{allowedTransactionId:e.transactionId})}var Y$=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function X$(e){return e.phase==="shape"?["summary","shared-understanding-confirmation"]:e.phase==="build"?e.approval==="confirmed"?["summary","artifact-or-no-code-reason"]:["summary","artifact-or-no-code-reason","shared-understanding-confirmation"]:e.phase==="verify"?["summary","verification-result","verification-report"]:[]}function De(e){let i=(e.findings??[]).filter(l=>!Wr(l.code)),n=i.find(l=>l.requiresUserDecision),r=i.find(l=>l.repairCommand!==null||Y$.test(l.code)),a=i.find(l=>l.code==="repair-iteration-limit"||l.code==="repair-override-exhausted"),o=i.find(l=>l.code==="repair-stagnation-stop"),s=[...new Set(i.map(l=>l.requiredAction))].sort();if(e.done)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"done",action:"none",command:null,requiresUserDecision:!1,requiredInputs:[]};if(a)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"]};if(n)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"work-phase",command:null,requiresUserDecision:!0,requiredInputs:s};if(o)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:null,requiresUserDecision:!1,requiredInputs:["new-repair-hypothesis"]};if(r)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"repair",command:r.repairCommand,requiresUserDecision:!1,requiredInputs:s};if(e.evidenceRetreat)return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"`,requiresUserDecision:!1,requiredInputs:["summary"]};if(e.state.phase==="build"&&e.state.verification_result==="fail")return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:["repair-verification-gaps"]};if(i.length>0)return e.state.phase==="archive"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"blocked",action:"none",command:null,requiresUserDecision:!1,requiredInputs:s}:s.includes("refresh-verification-receipts")?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:`comet native receipt refresh ${e.state.name} --apply`,requiresUserDecision:!1,requiredInputs:s}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"work-phase",command:null,requiresUserDecision:!1,requiredInputs:s};if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");return e.archiveConfirmation==="required"?{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"await-user",action:"archive",command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"]}:{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"archive",command:`comet native archive ${e.state.name} --expect-preflight ${e.archivePreflightHash}`,requiresUserDecision:!1,requiredInputs:[]}}return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",command:e.archiveReady?`comet native archive ${e.state.name} --dry-run`:null,requiresUserDecision:!1,requiredInputs:e.archiveReady?[]:["archive-readiness"]}}let c=e.state.phase==="shape"||e.state.phase==="build"&&e.state.approval!=="confirmed"?" --confirmed":"";return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.state.name,phase:e.state.phase,revision:e.state.revision,disposition:"continue",action:"advance-phase",command:`comet native next ${e.state.name} --summary "<summary>"${c}`,requiresUserDecision:!1,requiredInputs:X$(e.state)}}import Q$ from"path";var aS=10*1024*1024,j=class extends Error{},Qh=`Usage: comet native <command> [options]
203
203
 
204
204
  Commands:
205
205
  hook-guard [--hook-output copilot]
@@ -221,24 +221,24 @@ Commands:
221
221
  archive <change-name> --dry-run
222
222
  archive <change-name> --expect-preflight <sha256> [--confirmed]
223
223
  doctor [<change-name>] [--repair] [--strategy continue|rollback]
224
- `;function ut(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new j(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function X(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new j(`${t} may only be provided once`);if(i.length===0)return;let n=i[0],r=e[n+1];if(r===void 0||r.startsWith("--"))throw new j(`${t} requires a value`);return e.splice(n,2),r}function Ki(e,t){let i=[];for(let n=0;n<e.length;){if(e[n]!==t){n+=1;continue}let r=e[n+1];if(r===void 0||r.startsWith("--"))throw new j(`${t} requires a value`);i.push(r),e.splice(n,2)}return i}function G(e){if(e.length>0)throw new j(`Unexpected argument: ${e[0]}`)}function oe(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new j(`${t} is required`);return i}function tu(e,t="en"){let i=X(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new j("--language must be en or zh-CN");return i}function oS(e){let t=X(e,"--expect-revision");if(t!==void 0){if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new j("--expect-revision must be a positive integer");return Number(t)}}async function sS(e){return e?X$.resolve(e):Tc(process.cwd())}async function _e(e){let t=await _g({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function cS(e){let t=await le(e);return we(e,t?.native.artifact_root??"docs")}function ee(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
224
+ `;function ut(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new j(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function X(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new j(`${t} may only be provided once`);if(i.length===0)return;let n=i[0],r=e[n+1];if(r===void 0||r.startsWith("--"))throw new j(`${t} requires a value`);return e.splice(n,2),r}function Ki(e,t){let i=[];for(let n=0;n<e.length;){if(e[n]!==t){n+=1;continue}let r=e[n+1];if(r===void 0||r.startsWith("--"))throw new j(`${t} requires a value`);i.push(r),e.splice(n,2)}return i}function G(e){if(e.length>0)throw new j(`Unexpected argument: ${e[0]}`)}function oe(e,t){let i=e.shift();if(!i||i.startsWith("--"))throw new j(`${t} is required`);return i}function tu(e,t="en"){let i=X(e,"--language")??t;if(i!=="en"&&i!=="zh-CN")throw new j("--language must be en or zh-CN");return i}function oS(e){let t=X(e,"--expect-revision");if(t!==void 0){if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new j("--expect-revision must be a positive integer");return Number(t)}}async function sS(e){return e?Q$.resolve(e):Tc(process.cwd())}async function _e(e){let t=await _g({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function cS(e){let t=await le(e);return we(e,t?.native.artifact_root??"docs")}function ee(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
225
225
  `}}async function lS(e,t){try{let{bytes:i}=await un(e,t,{label:"Acceptance evidence entries file"});return i.toString("utf8")}catch(i){throw i instanceof Rt?i.reason==="not-regular-file"?new Error(`Acceptance evidence entries path is not a regular file: ${e}`,{cause:i}):i.reason==="too-large"?new Error(`Acceptance evidence entries file exceeds ${t} bytes: ${e}`,{cause:i}):new Error(`Acceptance evidence entries file changed while reading: ${e}`,{cause:i}):i}}async function uS(e){let t=[],i=0;for await(let n of process.stdin){let r=Buffer.isBuffer(n)?n:Buffer.from(String(n));if(i+=r.byteLength,i>e)throw new Error(`Acceptance evidence entries on stdin exceed ${e} bytes`);t.push(r)}return Buffer.concat(t).toString("utf8")}function dS(e,t){if(t instanceof j)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof as)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof va)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Cn)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof pi)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Wi)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Zh(e,t){return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
226
226
  `}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function fS(e,t){let i=oe(e,"change name"),n=ut(e,"--dry-run"),r=X(e,"--expect-preflight"),a=ut(e,"--confirmed");if(n&&r)throw new j("--dry-run and --expect-preflight cannot be combined");if(n&&a)throw new j("--confirmed is only valid with --expect-preflight");if(!n&&!r)throw new j("archive requires --dry-run or --expect-preflight <sha256>");if(r&&!/^[a-f0-9]{64}$/u.test(r))throw new j("--expect-preflight must be a SHA-256 hash");G(e);let{config:o,paths:s}=await _e(t);if(n){let u=await hr({paths:s,name:i}),d=await W(s,i);return ee("archive --dry-run",{...u,continuation:De({state:d,archiveReady:u.ready,archiveConfirmation:u.archiveConfirmation,archivePreflightHash:u.preflightHash})},`Native Archive preview ${u.preflightHash}: ${u.ready?"ready":"blocked"}
227
227
  `)}if(o.native.archive_confirmation==="required"&&!a)throw new j("archive requires --confirmed when native.archive_confirmation is required");let c=await W(s,i),l=await nS({paths:s,name:i,expectedPreflightHash:r});return ee("archive",{...l,continuation:De({state:c,done:!0})},`Archived Native change ${i} to ${l.archiveDir}
228
- `)}import{createHash as Q$}from"node:crypto";import{constants as ep,promises as Zt}from"node:fs";import mr from"node:path";import{TextDecoder as Z$}from"node:util";var hS={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},Se=class extends Error{constructor(i,n){super(n);this.kind=i}kind};function eH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function pS(e){let t=eH(e.scope.baseline),[i,n]=await Promise.all([bt({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),bn(e.paths,t,{origin:"explicit"})]),r=Tn({baseline:t,current:n,contractHash:e.scope.authority.contractHash,declaredArtifacts:e.scope.authority.declaredArtifacts,noCodeReason:e.scope.authority.noCodeReason,...e.scope.authority.gitChangedPaths?{gitChangedPaths:e.scope.authority.gitChangedPaths}:{}});return{contractHash:i.contract.contractHash,snapshotHash:r.scope.currentProjectionHash}}function mS(e,t){let i=(e??(()=>new Date))();if(!(i instanceof Date)||!Number.isFinite(i.getTime()))throw new Error(`Native check ${t} time is invalid`);return i.toISOString()}function tH(e,t,i){let n=[],r=i.scope.contractHash,a=i.scope.currentProjectionHash;return e.contractHash!==r&&n.push("contract-before-does-not-match-scope"),e.snapshotHash!==a&&n.push("implementation-before-does-not-match-scope"),t.contractHash!==e.contractHash&&n.push("contract-changed-during-check"),t.snapshotHash!==e.snapshotHash&&n.push("implementation-changed-during-check"),t.contractHash===e.contractHash&&t.contractHash!==r&&n.push("contract-after-does-not-match-scope"),t.snapshotHash===e.snapshotHash&&t.snapshotHash!==a&&n.push("implementation-after-does-not-match-scope"),n}function iH(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function iu(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function nH(e,t){let i=mr.resolve(e),n=mr.resolve(t);if(!$(i,n))throw new Se("unsafe-file","Scoped file parent escapes the project root");let r=[],a=i;for(let o of["",...mr.relative(i,n).split(mr.sep).filter(Boolean)]){o&&(a=mr.join(a,o));let s;try{s=await Zt.lstat(a)}catch(l){throw l.code==="ENOENT"?new Se("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new Se("unsafe-file","Scoped file parent is not a real directory");let c=await Zt.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Se("unsafe-file","Scoped file parent resolves outside the project");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:r[0].realPath,chain:r}}async function vS(e){for(let t of e){let i;try{i=await Zt.lstat(t.path)}catch(n){throw n.code==="ENOENT"?new Se("unsafe-file","Scoped file parent changed while reading"):n}if(!i.isDirectory()||i.isSymbolicLink()||!iH(t,i)||await Zt.realpath(t.path)!==t.realPath)throw new Se("unsafe-file","Scoped file parent changed while reading")}}async function rH(e){let t=mr.resolve(e.projectRoot,...e.file.path.split("/"));if(!$(e.projectRoot,t))throw new Se("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:i,chain:n}=await nH(e.projectRoot,mr.dirname(t)),r;try{r=await Zt.lstat(t)}catch(c){throw c.code==="ENOENT"?new Se("scope-mismatch","Scoped file no longer exists"):c}if(!r.isFile()||r.isSymbolicLink())throw new Se("unsafe-file","Scoped file is not a real regular file");if(r.size!==e.file.expected.size)throw new Se("scope-mismatch","Scoped file size no longer matches its projection");let a=await Zt.realpath(t);if(!$(i,a))throw new Se("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":ep.O_RDONLY|ep.O_NOFOLLOW|ep.O_NONBLOCK,s=await Zt.open(t,o).catch(c=>{throw c.code==="ENOENT"?new Se("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new Se("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),Zt.lstat(t),Zt.realpath(t)]);if(await vS(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!iu(r,c)||!iu(c,l))throw new Se("unsafe-file","Scoped file changed while opening");let d=[],f=Q$("sha256"),p=Buffer.allocUnsafe(64*1024),m=0;for(;;){let N=e.file.expected.size+1-m;if(N<1)throw new Se("scope-mismatch","Scoped file exceeds its projected size");let S=await s.read(p,0,Math.min(p.length,N),null);if(S.bytesRead===0)break;if(m+=S.bytesRead,m>e.file.expected.size)throw new Se("scope-mismatch","Scoped file exceeds its projected size");let R=Buffer.from(p.subarray(0,S.bytesRead));d.push(R),f.update(R)}let[h,v,b]=await Promise.all([s.stat(),Zt.lstat(t),Zt.realpath(t)]);if(await vS(n),m!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new Se("scope-mismatch","Scoped file content no longer matches its projection");if(!h.isFile()||!v.isFile()||v.isSymbolicLink()||b!==a||!$(i,b)||!iu(c,h)||!iu(c,v))throw new Se("unsafe-file","Scoped file changed while reading");let E=Buffer.concat(d,m);if(E.includes(0))return{bytes:m,text:null};try{return{bytes:m,text:new Z$("utf-8",{fatal:!0}).decode(E)}}catch{return{bytes:m,text:null}}}finally{await s.close()}}function aH(e){let t=new Map(e.current.entries.map(r=>[r.path,r])),i=[],n=[];for(let r of e.scope.changes){if(!r.after)continue;let a=t.get(r.path);if(!a||a.hash!==r.after.hash||a.size!==r.after.size||a.type!=="file"){n.push(r.path);continue}i.push({path:r.path,expected:r.after})}return i.sort((r,a)=>r.path.localeCompare(a.path,"en")),n.sort((r,a)=>r.localeCompare(a,"en")),{files:i,mismatches:n}}function oH(e,t,i){let n=t.split(`
229
- `);for(let r=0;r<n.length;r+=1){let a=n[r].endsWith("\r")?n[r].slice(0,-1):n[r],o=r+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&i({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:e,line:o,kind:"space-before-tab"})}}async function gS(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await gi(e.paths,e.state.name,e.state.implementation_scope),i=await pS({paths:e.paths,state:e.state,scope:t}),n=mS(e.clock,"start"),r=aH(t),a=[],o=0,s=N=>{o+=1,a.length<Pe.maxIssues&&a.push(N)},c=r.files,l=r.files.length+r.mismatches.length;if(t.scope.unresolvedScopes.some(N=>N.kind==="scope-detail-overflow")){let N=t.scope.changes.at(-1)?.path??t.current.entries.at(-1)?.path??t.baseline.entries.at(-1)?.path;if(!N)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:N,line:1,kind:"scan-limit"}),c=[]}else if(l>Pe.maxFiles){let N=[...r.files.map(S=>S.path),...r.mismatches].sort((S,R)=>S.localeCompare(R,"en"));s({path:N[Pe.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let N=0;for(let S of r.files){if(S.expected.size>Pe.maxFileBytes){s({path:S.path,line:1,kind:"scan-limit"}),c=[];break}if(N+=S.expected.size,N>Pe.maxTotalBytes){s({path:S.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let N of r.mismatches)s({path:N,line:1,kind:"scope-mismatch"});let d=0,f=0,p=0;for(let N of c)try{let S=await rH({projectRoot:e.paths.projectRoot,file:N});p+=S.bytes,S.text===null?(f+=1,s({path:N.path,line:1,kind:"binary-skipped"})):(d+=1,oH(N.path,S.text,s))}catch(S){if(!(S instanceof Se))throw S;s({path:N.path,line:1,kind:S.kind})}let m=await pS({paths:e.paths,state:e.state,scope:t}),h=mS(e.clock,"end"),v=tH(i,m,t);a.sort((N,S)=>N.path.localeCompare(S.path,"en")||N.line-S.line||hS[N.kind]-hS[S.kind]);let b=Yy({change:e.state.name,sourceRevision:e.state.revision,status:o===0&&v.length===0?"passed":"failed",startedAt:n,endedAt:h,contract:{expectedHash:t.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:d,binaryFilesSkipped:f,bytesScanned:p,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:v.length>0,staleReasons:v}),E=await vb({paths:e.paths,name:e.state.name,receipt:b});return{receipt:Li(b),ref:E}}async function wS(e){return re(e.paths,`check ${e.name}`,()=>He(e.paths,e.name,`check ${e.name}`,()=>tp(e)))}async function tp(e){await St(e.paths,e.name);let t=await W(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native check requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await gS({paths:e.paths,state:t}),n=await Sb({paths:e.paths,state:t,checkReceipt:i.receipt,checkReceiptRef:i.ref});return{change:t,receipt:i.receipt,checkRef:i.ref,ref:n.ref}}async function yS(e,t){let i=oe(e,"change name");G(e);let{paths:n}=await _e(t),r=await wS({paths:n,name:i}),a={ref:r.ref,hash:r.receipt.receiptHash,status:r.receipt.status,checker:r.receipt.checker,counts:r.receipt.counts,issues:r.receipt.issues,issuesTruncated:r.receipt.issuesTruncated,stale:r.receipt.stale,staleReasons:r.receipt.staleReasons,startedAt:r.receipt.startedAt,endedAt:r.receipt.endedAt,sourceRevision:r.receipt.sourceRevision},o=r.receipt.status==="passed"&&!r.receipt.stale;return{command:"check",exitCode:o?0:1,data:a,text:`Native check ${o?"passed":"failed"}: ${r.ref}
230
- `}}import HS from"path";import{promises as gH}from"fs";import sH from"path";function ip(e,t){return sH.resolve(e,...t.split(/[\\/]/u))}async function nu(e,t){let i=[],n=C(e,t.name),r=ip(n,at.stateRef),a;try{a=await ye(n)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:r}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:r}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:r}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:r}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:r}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:r});let o=ip(n,a.trajectoryRef),s=await zr(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await qe(n,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ip(n,a.checkpointRef);try{let u=await Jr(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import os from"path";var NS=8,cH={"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function lH(e){let t=cH[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Wr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function uH(e,t,i){if(!i.path)return null;let n;if(os.isAbsolute(i.path)?n=os.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=os.resolve(C(e,t.name),...i.path.split(/[\\/]/u)):n=os.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,n))return null;let r=os.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function dH(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function ei(e){return e.findings.map(t=>{let i=lH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:uH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:dH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let n={error:0,warning:1,info:2};return n[t.severity]-n[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function bS(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,NS),truncated:t.length>NS}}import SS from"path";var kS=240,ES=8,ru=50;function RS(e){let t=Array.from(e);return t.length<=kS?e:`${t.slice(0,kS-1).join("")}…`}function fH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function hH(e){let t=[...new Set(e.map(fH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,ES),reasonCount:e.length,codesTruncated:t.length>ES};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,ru),reasonsTruncated:e.length>ru}}}async function CS(e){let t=null;try{let s=await zi(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Ji(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Ji(e.paths,e.state.name)}}let i=await ub({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=hH(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Xt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:RS(i.checkpoint.summary),nextAction:RS(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:SS.relative(e.paths.projectRoot,SS.join(C(e.paths,e.state.name),...i.checkpoint.manifestRef.split("/"))).replaceAll("\\","/"),artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Xt.maxArtifacts}}function pH(e){if(e.phase!=="build"||e.verification_result!=="fail"||!e.implementation_scope||!e.verification_evidence)throw new Error("Native repair guard requires a failed Verify-to-Build state")}async function PS(e,t){let i=C(e,t.name),n=await ye(i);if(!n||!t.run_id||n.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let r=await Jr(i,n.checkpointRef);if(!r||r.runId!==n.runId||r.stateVersion!==n.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await qe(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function np(e,t){let i=await PS(e,t);return{committed:i,latest:RN(i),history:EN(i)}}function mH(e,t){let i=e.latest;if(!i)return null;let n=e.history.filter(l=>l.kind==="failure"),r=n.length===0?0:Vo({signatureHash:i.signatureHash,...i.contractHash===null?{}:{failedAcceptanceIds:i.failedAcceptanceIds,failedCheckIds:i.failedCheckIds}},n.slice(0,-1)),a=i.overrideSummaryHash!==null,o=e.history.some(l=>l.kind==="override"&&l.signatureHash===i.signatureHash),s=n.length>=t,c=i.disposition==="hard-stop"&&!s?"continue":i.disposition;return{disposition:s?"hard-stop":c,reasonCode:a?"override-accepted":o&&i.disposition==="manual-stop"?"override-already-used":s?"repair-iteration-limit":i.disposition==="manual-stop"?"repeated-failure-stop":i.disposition==="warn"?"repeated-failure-warning":"new-failure-signature",signatureHash:i.signatureHash,consecutiveFailures:r,totalRepairFailures:n.length,remainingIterations:Math.max(0,t-n.length),overrideAccepted:a}}async function AS(e,t,i){return mH(await np(e,t),i)}function xS(e){return{disposition:e.decision.disposition,reasonCode:e.decision.reasonCode,signatureHash:e.decision.signature.signatureHash,consecutiveFailures:e.decision.consecutiveFailures,totalRepairFailures:e.decision.totalRepairFailures,remainingIterations:e.decision.remainingIterations,overrideAccepted:e.decision.overrideAccepted}}function vH(e){return sa(e.filter(t=>t.status!=="passed").map(t=>Zy(t)))}async function TS(e){if(!e.state.implementation_scope)throw new Error("Native repair failure has no implementation scope");let t=[...new Set([...e.envelope.requiredReceiptRefs,...e.envelope.receiptRefs])],[i,n,r]=await Promise.all([PS(e.paths,e.state),gi(e.paths,e.state.name,e.state.implementation_scope),Promise.all(t.map(o=>oa(e.paths,e.state.name,o)))]),a=vH(r);return PN({...i,envelope:e.envelope,implementationScope:n,maxVerifyFailures:e.maxVerifyFailures,...a.length>0?{failedCheckIds:a}:{}})}async function _S(e){let t=await np(e.paths,e.state),i=t.latest,n=Wt(e.currentImplementationScope).scope.contractHash;if(i?.contractHash!==null&&i?.contractHash!==n){if(e.override)throw new Error("Native repair override cannot cross a confirmed contract change");return{disposition:"proceed",eventProjection:null}}let r=t.history.filter(u=>u.kind==="failure").length;if(i&&r>=e.maxVerifyFailures){if(e.override)throw new Error("Native repair hard stop cannot be overridden");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash)}}let a=i?.disposition==="hard-stop"&&r<e.maxVerifyFailures?"continue":i?.disposition;if(!i||a!=="manual-stop"&&a!=="hard-stop"){if(e.override)throw new Error("Native repair override requires the latest manual stop");return{disposition:"proceed",eventProjection:null}}let o=t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash);if(!(e.state.phase==="build"&&e.state.verification_result==="fail"&&e.state.implementation_scope!==null&&e.state.verification_evidence!==null)){if(e.override)throw new Error("Native repair override requires an active failed Verify-to-Build state");return{disposition:"proceed",eventProjection:null}}pH(e.state);let[c,l]=await Promise.all([On(e.paths,e.state.name,e.state.verification_evidence),gi(e.paths,e.state.name,e.state.implementation_scope)]);if(l.scope.scopeHash!==c.implementationScopeHash)throw new Error("Native repair verification evidence does not match its implementation scope");if(i.contractHash===null&&la(e.currentImplementationScope)!==la(l)){if(e.override)throw new Error("Native repair override is not valid after implementation scope progress");return{disposition:"proceed",eventProjection:null}}if(i.disposition==="hard-stop"){if(e.override)throw new Error("Native repair hard stop cannot be overridden without implementation progress");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}}return o?{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}:e.override?{disposition:"proceed",eventProjection:CN({...t.committed,override:e.override}).eventProjection}:{disposition:"manual-stop",signatureHash:i.signatureHash,overrideRecorded:!1}}async function IS(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await np(e,t),r=n.latest;if(!r)return null;let a=n.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=r.disposition==="hard-stop"&&!o?"continue":r.disposition;return{disposition:o?"hard-stop":s,signatureHash:r.signatureHash,overrideRecorded:n.history.some(c=>c.kind==="override"&&c.signatureHash===r.signatureHash),failedAcceptanceIds:[...r.failedAcceptanceIds],failedCheckIds:[...r.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var wH=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,ga=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function yH(e){try{return(await rs(e))?.change??null}catch{return null}}function NH(e,t,i=!1,n){return e.phase==="archive"?t?`comet native archive ${e.name} --dry-run`:i?`comet native next ${e.name} --summary "<summary>"`:null:`comet native next ${e.name} --summary "<summary>"${e.phase==="shape"||e.phase==="build"&&e.approval!=="confirmed"?" --confirmed":""}`}async function bH(e,t){let i=C(e,t.name),n=[...(await ir(i,t.brief)).findings,...(await Xr(e,t)).findings,...await nu(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await hi(e,t.name);if(r===null)n.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Nn(e,r);a.complete||n.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(r){n.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${r.message}`})}if(t.phase==="build")try{let r=await bt({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==r.contract.contractHash&&n.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(r){n.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${r.message}`})}try{await yi(e,t.name)&&n.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(r){n.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${r.message}`})}return t.verification_report?n.push(...(await Yr(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&n.push({code:"verification-report-missing",message:"Native change has no verification report"}),n}async function Ye(e,t,i){let n=await yH(e)===t,r;try{let y=await ot(e,t);if(y.status==="migration-required"&&y.state)return{name:t,phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};r=y.state}catch(y){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,error:y.message}}let a=await CS({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await IS(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let y=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:y,message:`Native repair is stopped at failure signature: ${o.signatureHash}`})}}catch{s.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let c;if(i?.details&&(r.phase==="build"||r.phase==="verify"||r.phase==="archive"))try{let y=await bt({changeDir:C(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),g=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let k=await On(e,r.name,r.verification_evidence);for(let x of k.acceptanceTrace.entries)g.set(x.acceptanceId,x.status==="failed"?"failed":x.status==="missing"?"missing":"satisfied")}c=Ll({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:g,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(y){if(i.acceptanceCursor)throw y;c=void 0}let l=[];try{let y=await Tl(e,r.name);l.push(...y.findingCodes.map(g=>({code:g,message:`Native change overlap is visible in the current root: ${g}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let y=await ul(e,r.name);if(y){let g=await Ww({paths:e,identity:y});u.push(...g.findingCodes.map(k=>({code:k,message:`Native workspace advisory changed: ${k} (${g.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-inspection-unavailable",message:"Native workspace advisory could not be recomputed safely"})}let d=[],f=!1;if(r.phase==="verify"){let y=await es({paths:e,state:r});f=y.freshness!=="fresh",d.push(...y.findingCodes.map(g=>({code:g,message:`Native Verify implementation scope is not current: ${g}`})))}let p=null,m=[];if(r.phase==="archive")try{p=await hr({paths:e,name:r.name}),m.push(...p.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let h=[...await bH(e,r),...a.findings,...l,...u,...d,...s,...m].filter((y,g,k)=>k.findIndex(x=>x.code===y.code&&x.path===y.path)===g),v=ei({paths:e,state:r,findings:h}),b=v.filter(y=>!Wr(y.code)),E=r.phase==="archive"&&p?.ready===!0&&b.length===0,N=f||r.phase==="archive"&&(p?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),S=v.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",w=v.find(y=>y.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:S||R?null:NH(r,E,N,i?.clarificationMode),archiveReady:E,inspection:a.inspection,findingSummary:bS(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:De({state:r,findings:v,archiveReady:E,evidenceRetreat:N,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:v.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:ru,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...w?{error:w.message}:{}}}async function SH(e){let t;try{t=await ui({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await gH.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>ga.maxChanges))throw new Error(`Native status exceeds ${ga.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function jS(e,t){let i=t.toString(36),n=H("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function kH(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=wH.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let n=H("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==n)throw new Error("Native status cursor integrity check failed");return i}async function rp(e,t){let i=await SH(e),n=H("comet.native.status-names.v1",i),r=kH({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+ga.maxItems).map(c=>Ye(e,c,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let c of a){let l=[...o,c],u=r+l.length,d={schema:"comet.native.status-page.v1",total:i.length,offset:r,items:l,nextCursor:u<i.length?jS(n,u):null,limits:{...ga}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ga.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(c)}let s=r+o.length;return{schema:"comet.native.status-page.v1",total:i.length,offset:r,items:o,nextCursor:s<i.length?jS(n,s):null,limits:{...ga}}}async function ap(e,t){return(await rp(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{randomUUID as EH}from"crypto";function OS(e,t){let i=Ne(e).trim();if(i.length===0||i.length>2e3)throw new Error(`${t} must be between 1 and 2000 characters`);return i}function RH(e){if(e!==void 0){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native expected revision must be a positive integer");return e}}async function $S(e){let t=OS(e.summary,"Checkpoint summary"),i=OS(e.nextAction,"Checkpoint next action"),n=RH(e.expectedRevision);return re(e.paths,`checkpoint ${e.name}`,()=>He(e.paths,e.name,`checkpoint ${e.name}`,async()=>{await St(e.paths,e.name);let r=await W(e.paths,e.name),a=await sb(e.paths,e.name,e.artifacts??[]),o=Yo(a),s=F(JSON.stringify({summary:t,nextAction:i,artifacts:a.artifacts})),c=await $h(e.paths,e.name);if(c?.inputHash===s&&c.stateRevision===r.revision&&c.phase===r.phase){if(n!==void 0&&n!==c.previousRevision&&n!==r.revision)throw new Cn(r.name,n,r.revision);return{change:r,checkpoint:c,idempotent:!0,expectedRevision:n??c.previousRevision,previousRevision:c.previousRevision,revision:r.revision,outcome:"idempotent",continuation:De({state:r})}}if(n!==void 0&&r.revision!==n)throw new Cn(r.name,n,r.revision);let l={...r,revision:r.revision+1},u={schema:"comet.native.progress-checkpoint.v1",id:e.checkpointId?.()??EH(),change:r.name,phase:r.phase,previousRevision:r.revision,stateRevision:l.revision,summary:t,nextAction:i,inputHash:s,manifestHash:o,manifestRef:Ih(o),artifactCount:a.artifacts.length,createdAt:(e.now??new Date).toISOString()},d=await db({paths:e.paths,previousState:r,nextState:l,checkpoint:u,manifest:a,now:e.now,checkpointId:()=>u.id});await e.hooks?.afterPrepared?.(d);let f=await Xo(e.paths,e.name,e.hooks);if(!f)throw new Error("Native checkpoint journal disappeared before completion");return{change:f.nextState,checkpoint:f.checkpoint,idempotent:!1,expectedRevision:n??f.checkpoint.previousRevision,previousRevision:f.checkpoint.previousRevision,revision:f.nextState.revision,outcome:"recorded",continuation:De({state:f.nextState})}}))}async function DS(e,t){let i=oe(e,"change name"),n=X(e,"--summary");if(!n)throw new j("--summary is required");let r=X(e,"--next-action");if(!r)throw new j("--next-action is required");let a=Ki(e,"--artifact"),o=oS(e);G(e);let{config:s,paths:c}=await _e(t),l=await $S({paths:c,name:i,summary:n,nextAction:r,artifacts:a,expectedRevision:o}),u=await Ye(c,i,{clarificationMode:s.native.clarification_mode,maxVerifyFailures:s.native.max_verify_failures}),d=HS.relative(c.projectRoot,HS.join(C(c,i),...l.checkpoint.manifestRef.split("/"))).replaceAll("\\","/");return ee("checkpoint",{...l,checkpoint:{...l.checkpoint,manifestRef:d},continuation:u.continuation})}import{promises as k0}from"fs";import Fe from"path";import{createHash as JH,randomUUID as zH}from"node:crypto";import{constants as up,promises as ie}from"node:fs";import he from"node:path";var su=Nu(mc(),1);import{randomUUID as CH}from"crypto";import{promises as BS}from"fs";import sp from"path";import{isDeepStrictEqual as cp}from"util";var vr=/^[a-f0-9]{64}$/u,PH=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),AH=new Set(["sourceHash","targetHash","nextJournal"]),xH=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),MS=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),TH=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function au(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function FS(e){return JSON.stringify(e,null,2)+`
231
- `}function lp(e){return e.schema===Oe?dl(e):Rn(e)}function op(e,t){return{...e,schema:Oe,minimum_runtime_version:2,revision:t}}function _H(e){return{...e,schema:Ii,minimum_runtime_version:2,revision:1,previousState:op(e.previousState,1),nextState:op(e.nextState,2)}}function ou(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ce,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function IH(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:_i,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:ou(e.previousState),nextState:{...ou(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:ct.definition.metadata.version,skillHash:cr}:e.nextRun}}function LS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function wa(e,t){return JSON.stringify(dl(e))===JSON.stringify(dl(t))}function qS(e,t){return JSON.stringify(Rn(e))===JSON.stringify(Rn(t))}function Gi(e,t){return cp(e,t)}function jH(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let r=e;if(au(r,xH,"Schema migration transition supersede plan"),typeof r.sourceHash!="string"||!vr.test(r.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof r.transitionId!="string"||r.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof r.evidenceHash!="string"||!vr.test(r.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=kn(r.previousRun),o=kn(r.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Gi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!r.eventData||typeof r.eventData!="object"||Array.isArray(r.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=r.eventData,u=Object.keys(l);if(u.length!==MS.size||u.some(f=>!MS.has(f))||l.fromSchema!==Oe||l.toSchema!==Ce||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==r.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:r.transitionId,migrationId:n,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(r.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:r.sourceHash,transitionId:r.transitionId,previousRun:a,nextRun:o,evidenceHash:r.evidenceHash,eventData:l}}function ss(e,t){return sp.join(C(e,t),"runtime","schema-migration.json")}function OH(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");au(e,PH,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let n=i.fromSchema===Tt&&i.toSchema===Oe,r=i.fromSchema===Oe&&i.toSchema===Ce;if(!n&&!r)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!vr.test(i.sourceHash)||typeof i.targetHash!="string"||!vr.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=n?Pn(i.nextState):_t(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,su.stringify)(lp(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");au(i.transition,AH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!vr.test(l.sourceHash)||typeof l.targetHash!="string"||!vr.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=n?bh(l.nextJournal,t):Fl(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+`
232
- `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===Oe?wa(a,u.previousState)||wa(a,u.nextState):a.schema===Ce&&(qS(a,u.previousState)||qS(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(n&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!r||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ce)throw new Error("Schema migration transition supersede target schema is invalid");s=jH(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!r||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");au(i.runRetreat,TH,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=kn(l.previousRun),d=kn(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!vr.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ce||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function cs(e,t){let i=ss(e,t);await A(e.nativeRoot,i);try{let n=await Lc({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return OH(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function $H(e,t,i){let n=await hi(e,t),r=n?await Nn(e,n):await bo(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=el(r),o=r.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=r.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new pi(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await tl(e,t,r)}async function VS(e){try{return await rt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function HH(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function JS(e,t){let i=t.transitionSupersede,n=C(e,t.change),r=await qe(n,i.nextRun.trajectoryRef),a=r.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!cp(o.event,HH(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:r.length,sequence:o?.event.sequence??null}}async function DH(e,t,i){if(!t.transitionSupersede)return;let n=Be(e,t.change),r=await VS(n);if(r===t.transitionSupersede.sourceHash)return;if(r!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${r}`);let a=await ye(C(e,t.change)),o=await JS(e,t),s=await Jr(C(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!Gi(a,t.transitionSupersede.nextRun)||o.sequence===null||!s||s.runId!==t.transitionSupersede.nextRun.runId||s.stateVersion!==t.transitionSupersede.nextRun.iteration||s.trajectoryOffset!==o.sequence||s.contextHash!==null||s.artifactsHash!==F(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function MH(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=C(e,t.change),a=await ye(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Gi(a,n.nextRun)){if(!Gi(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Zn(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!Gi(await ye(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await JS(e,t);if(o.sequence===null){let l=await Hn({changeDir:r,run:n.nextRun,type:"state_migrated",data:{...n.eventData,migrationId:t.id,evidenceHash:n.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await lr({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Be(e,t.change),c=await VS(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await BS.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function FH(e,t,i){if(!t.runRetreat)return;let n=C(e,t.change),r=await ye(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Gi(r,t.runRetreat.nextRun)){if(!Gi(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Zn(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await qe(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Hn({changeDir:n,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await lr({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function LH(e,t,i){let n=await cs(e,t);if(!n)return null;if(await Kr(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=sp.join(C(e,t),$e),a=await rt(r);if(await DH(e,n,a===n.targetHash),await $H(e,t,n.createdAt),a!==n.targetHash){if(a!==n.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${n.sourceHash}, actual ${a}`);await je(r,(0,su.stringify)(lp(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=Be(e,t),s=await rt(o);if(s!==n.transition.targetHash){if(s!==n.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${n.transition.sourceHash}, actual ${s}`);await de(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await MH(e,n,i),await FH(e,n,i),await BS.rm(ss(e,t),{force:!0}),n.nextState}async function qH(e){let t=C(e.paths,e.state.name),i=await ye(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let n={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},r=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:Oe,toSchema:Ce,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function BH(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let r=wa(i,t.previousState),a=wa(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=C(e.paths,i.name),s=await ye(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Gi(s,t.previousRun),l=Gi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await qe(o,t.nextRun.trajectoryRef)).map((b,E)=>({event:b,index:E})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!cp(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...ou(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await rt(Be(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:h,evidenceHash:v,eventData:{fromSchema:Oe,toSchema:Ce,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function VH(e){let t,i,n,r;if(e.state.schema===Tt){if(t=op(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==er)throw new Error("Native v1 change has a transition from another schema generation");let s=_H(e.pendingTransition.journal);if(LS(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(LS(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Be(e.paths,e.name);i={sourceHash:await rt(c),targetHash:F(FS(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ii)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await BH({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=IH(s);if(wa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(wa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Be(e.paths,e.name);i={sourceHash:await rt(u),targetHash:F(FS(l)),nextJournal:l}}}else t=ou(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await qH({paths:e.paths,state:e.state,migrationId:e.id}));let a=sp.join(C(e.paths,e.name),$e),o=(0,su.stringify)(lp(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Tt?Oe:Ce,sourceHash:await rt(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function zS(e){return re(e.paths,`migrate schema for ${e.name}`,()=>He(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await LH(e.paths,e.name,e.hooks);if(i?.schema===Ce)return i;let n=await ot(e.paths,e.name);if(n.status==="current"&&n.state)return n.state;if(n.status!=="migration-required"||!n.state)throw new Error(n.message??`Native change ${e.name} cannot be migrated`);if(await Kr(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=n.state;if(r.schema!==Tt&&r.schema!==Oe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Sh(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await VH({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??CH()}),s=ss(e.paths,e.name);await A(e.paths.nativeRoot,s),await de(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Yi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),WH=512*1024,gr=/^([a-f0-9]{64})\.json$/u,UH=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,KH=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,cu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function fp(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ri(e,t){return fp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function YS(e,t){return fp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function ya(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ze(e,t){return e<t?-1:e>t?1:0}function GH(e,t){let i=he.relative(e.projectRoot,t);if(i.length===0||he.isAbsolute(i)||i===".."||i.startsWith(`..${he.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(he.sep).join("/")}function XS(e,t){return he.join(C(e,t),"runtime","evidence")}function lu(e,t){return GH(e,XS(e,t))}async function uu(e,t){let i=he.resolve(e),n=he.resolve(t);if(!$(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=he.relative(i,n).split(he.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=he.join(o,s));let c=await ie.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await ie.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...ya(c)})}return a}async function Ht(e){for(let t of e){let i=await ie.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!fp(t,i)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function QS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:wt(e,t)}function WS(e){return e!==null&&KH.test(e)?[e]:[]}function YH(e,t,i,n){if(e==="snapshots")return{canonical:ea(i,t),dependencies:[]};if(e==="scopes"){let a=ta(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Fo(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[wt("scopes",a.scopeHash)]}}if(e==="verifications"){let a=na(i);if(a.change!==n||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(WS));return{canonical:a,dependencies:[a.implementationScopeRef,aN(a.reportHash),...WS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||JH("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Bo(i);if(a.bindings.change!==n||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let r=Li(i);if(r.change!==n||r.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:r,dependencies:[]}}async function Ln(e){let t=await ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?WH:Gt;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await ie.realpath(e.file);if(!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":up.O_RDONLY|up.O_NOFOLLOW|up.O_NONBLOCK,a=await ie.open(e.file,r).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Ht(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!Ri(ya(t),o)||!Ri(ya(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let E=i+1-d,N=await a.read(u,0,Math.min(u.length,E),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,N.bytesRead)))}let[f,p,m]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Ht(e.directoryChain),!p.isFile()||p.isSymbolicLink()||m!==n||!Ri(ya(o),f)||!Ri(ya(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(h)}catch(E){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:E})}let b=YH(e.kind,e.hash,v,e.name);if(h!==JSON.stringify(b.canonical,null,2)+`
233
- `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:ya(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(Ze)}}finally{await a.close()}}async function US(e){try{return await ie.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function XH(e){let t=C(e.paths,e.name),i=XS(e.paths,e.name);await A(e.paths.nativeRoot,i);let n;try{let o=await uu(t,i);n=await ie.readdir(i,{withFileTypes:!0}),await Ht(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of cu){if(!n.some(d=>d.name===o))continue;let s=he.join(i,o),c=await uu(t,s),l=(await ie.readdir(s,{withFileTypes:!0})).sort((d,f)=>Ze(d.name,f.name)),u=new Map;for(let d of l){let f=UH.exec(d.name);if(!f)continue;let p=u.get(f[1])??[];p.push(d),u.set(f[1],p)}for(let[d,f]of[...u.entries()].sort(([p],[m])=>Ze(p,m))){if(f.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${o}/${d}`);let p=f[0];if(!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${o}/${p.name}`);let m=he.join(s,d),h=gr.exec(d)?.[1];if(!h)throw new Error(`Native evidence cleanup quarantine name is invalid: ${p.name}`);let v=QS(o,h),b=he.join(s,p.name),E=await Ln({changeRoot:t,file:b,ref:v,kind:o,hash:h,name:e.name,directoryChain:c}),N=await US(m),S=N?null:await Ln({changeRoot:t,file:m,ref:v,kind:o,hash:h,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:b,document:E,action:N?"restore-original":"finish-linked-recovery",originalDocument:S})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(Ze);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Na(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${du(a)}`),path:lu(e.paths,e.name)}]};for(let o of r.sort((s,c)=>Ze(s.ref,c.ref))){if(await Ht(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Ln({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Ln({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!Ri(o.originalDocument.identity,u.identity)||!Ri(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await ie.rm(o.quarantine),await Ht(o.document.directoryChain);continue}if(!await US(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await ie.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!Ri(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await ie.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Ln({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Ln({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!YS(o.document.identity,c.identity)||!Ri(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await ie.rm(o.quarantine),await Ht(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Na(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${du(a)}`),path:lu(e.paths,e.name)}]}}async function QH(e,t){let i=C(e,t),n=he.join(i,"runtime","evidence");await A(e.nativeRoot,n);let r;try{let c=await uu(i,n);r=await ie.readdir(n,{withFileTypes:!0}),await Ht(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!cu.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(Ze);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${du(a)}`);let o=[],s=0;for(let c of cu){if(!r.some(f=>f.name===c))continue;let l=he.join(n,c),u=await uu(i,l),d=(await ie.readdir(l,{withFileTypes:!0})).sort((f,p)=>Ze(f.name,p.name));await Ht(u);for(let f of d){if(o.length>=Yi.maxDocuments)throw new Error(`Native evidence store exceeds ${Yi.maxDocuments} documents`);let p=gr.exec(f.name);if(!p||!f.isFile()||f.isSymbolicLink())throw new Error(`Native evidence kind ${c} has an unknown or special entry: ${f.name}`);let m=QS(c,p[1]),h=he.join(l,f.name);await A(e.nativeRoot,h);let v=await Ln({changeRoot:i,file:h,ref:m,kind:c,hash:p[1],name:t,directoryChain:u});if(s+=v.size,s>Yi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Yi.maxScannedBytes} scanned bytes`);o.push(v)}await Ht(u)}return o}function KS(e,t){let i=new Set,n=[...e].sort(Ze).reverse();for(;n.length>0;){let r=n.pop();if(i.has(r))continue;let a=t.get(r);if(!a)throw new Error(`Native evidence dependency is missing: ${r}`);i.add(r);for(let o of[...a.dependencies].sort(Ze).reverse())i.has(o)||n.push(o)}return i}function ZH(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let n=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ze),r=[];for(;n.length>0;){let a=n.shift(),o=t.get(a);r.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(n.push(s),n.sort(Ze))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function e0(e,t,i){let n=new Map(e.map(c=>[c.ref,c]));if(n.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!n.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let r=KS(t,n),a=new Set(r);for(let c of e)i-c.mtimeMs<Yi.minimumAgeMs&&a.add(c.ref);for(let c of cu){let l=e.filter(u=>u.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ze(u.ref,d.ref)).slice(0,Yi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=KS(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Yi.minimumAgeMs).sort((c,l)=>Ze(c.ref,l.ref));return{candidates:ZH(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function du(e){let t=e.slice(0,Yi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Na(e){let t=Yi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function dp(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(Ze);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Na(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${du(r)}`),path:n}}async function GS(e,t){try{await ie.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await ie.rename(e,t)}catch{}}async function t0(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ht(e.directoryChain);let i=await Ln({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:gr.exec(he.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await ie.lstat(e.file),r=await ie.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!Ri(e.identity,n)||!Ri(e.identity,i.identity)||!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=he.join(he.dirname(e.file),`.${he.basename(e.file)}.${zH()}.gc`);await ie.rename(e.file,a);try{let[o,s]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Ht(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!YS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await GS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await ie.rm(a),await Ht(e.directoryChain)}catch(o){throw await GS(a,e.file),o}}async function i0(e){if((await le(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await ie.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())return!0;try{let r=await nt(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function n0(e,t){if(t)return[t];let i;try{i=await ie.readdir(e.changesDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort(Ze)}async function r0(e,t){let i=await ot(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([yi(e,t),cs(e,t),zi(e,t)]);return n!==null||r!==null||a!==null}async function a0(e){if(await r0(e.paths,e.name))return[];let t=await ot(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await XH({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let n=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&n.push(c);let r=await QH(e.paths,e.name),a=e0(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=lu(e.paths,e.name);if(!e.repair)return[...i.findings,dp(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await t0(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[dp(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Na(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,dp(e.name,a,!0,o)]}async function ZS(e){if(e.deferAll||await i0(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async r=>{let a=[];for(let o of await n0(e.paths,e.name))try{a.push(...await a0({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Na(`Native evidence retention refused to clean ${o}: ${s.message}`),path:lu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let n=await i(!1);if(n.some(r=>r.severity==="error")||!n.some(r=>r.code==="evidence-retention-candidates"||r.code==="evidence-retention-recovery-required"))return n;try{return await re(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Na(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as o0,randomUUID as s0}from"crypto";import{promises as wr}from"fs";import ae from"path";var pp=64*1024*1024,c0=256*1024,nk=16*1024*1024;async function Me(e){try{return await wr.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function l0(e){let t;try{t=await wr.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let n;try{n=await nt(e,i.name)}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:r}):r}if(n.status!=="committed"&&n.status!=="rolled-back")throw new Error(`Native transaction ${n.id} is unfinished; recover it before moving`)}}async function u0(e,t){for(let i of await wr.readdir(e.locksDir,{withFileTypes:!0})){let n=ae.join(e.locksDir,i.name);if(ae.resolve(n)!==ae.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${n}`)}}async function d0(e){let t;try{t=await wr.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let n;try{n=await ot(e,i.name)}catch{continue}n.status!=="current"||!n.state||!("revision"in n.state)||await Ao({paths:e,name:i.name,revision:n.state.revision})}}async function us(e,t){let i=[];async function n(r){let a=await pt({root:e,directory:r,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(r,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await wr.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await ue({root:e,file:c,maxBytes:pp,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await n(e),i.sort((r,a)=>r.ref.localeCompare(a.ref))}async function f0(e,t,i,n){await di({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await pt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await wr.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await di({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ai({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:pp,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await r(e,t)}async function ba(e,t,i,n){let r=await us(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await us(t,{rejectSymlinks:!0,excludedFiles:n?new Set([ae.resolve(n)]):void 0});if(JSON.stringify(r)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function rk(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function h0(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function p0(e){return`${e}.removing`}function ek(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function ak(e,t,i){return ae.join(zc(e,t).directory,`root-move-cleanup-${i}.json`)}function m0(e){return JSON.stringify(e,null,2)+`
234
- `}function v0(e){return o0("sha256").update(e).digest("hex")}function g0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,n=Object.keys(i).sort(),r=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function w0(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let n=e;if(JSON.stringify(Object.keys(n).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||n.schema!=="comet.native.root-move-cleanup.v1"||n.transactionId!==t||n.kind!==i||!Array.isArray(n.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let r=n.entries.map(g0);for(let a=0;a<r.length;a+=1){if(a>0&&r[a-1].ref.localeCompare(r[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(r[a].ref);if(o!=="."&&!r.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:r}}async function y0(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=m0(t);if(Buffer.byteLength(i,"utf8")>nk)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await je(ak(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),v0(i)}async function N0(e){let t=await ue({root:e.paths.nativeRoot,file:ak(e.paths,e.id,e.cleanup.kind),maxBytes:nk,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return w0(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function hp(e){let t=await us(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(n=>[n.ref,n]));for(let n of t){let r=i.get(n.ref);if(!r||JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${n.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function tk(e){return e.ref.split("/").length}async function b0(e){let i=[...await hp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>tk(a)-tk(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=ae.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await qc({root:e.projectRoot,file:a,maxBytes:pp,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await Sf({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${r.ref}`}),n+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,r.ref,n)}await hp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Sf({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function fu(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function ok(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function S0(e,t,i,n){for(let a of[e,t])try{let o=await nt(a,n);if(o.kind!=="root-move")throw new Error(`Transaction ${n} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let r=ae.join(i,"runtime","transactions",n,"transaction.json");try{let a=await ue({root:i,file:r,maxBytes:c0,label:`Staged Native root-move journal ${n}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${n}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${n}`,{cause:a})}}async function ik(e){let t=fu(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await oi(e.projectRoot,t),t}async function ls(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=fu(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await oi(e.projectRoot,i),i}async function hu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let n=i.cleanup;if(n&&n.kind!==e.kind)throw new Error(`Native root move has unfinished ${n.kind} cleanup; cannot start ${e.kind}`);let r=await Me(e.target),a=await Me(e.quarantine);if(r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!n){if(!r&&!a)return t;if(!r&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await y0({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await us(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await ls({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await N0({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await Me(e.target),a=await Me(e.quarantine),r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(r){if(n.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Bg({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(n.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ls({projectRoot:e.projectRoot,config:t,id:e.id})}return await hp({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await ls({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await ls({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await b0({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ls({projectRoot:e.projectRoot,config:t,id:e.id})}async function sk(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Me(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=p0(e.staging);t=await hu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await us(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await f0(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await ba(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await ik({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Me(e.destinationPaths.nativeRoot)){if(await Me(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await ba(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Me(e.staging))throw new Error("Native move staging tree is missing");await ba(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await wr.rename(e.staging,e.destinationPaths.nativeRoot)}t=await ik({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Me(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=h0(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Me(e.sourcePaths.nativeRoot)&&await ba(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await hu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:n,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await d0(e.destinationPaths);let r=await nt(e.destinationPaths,e.pending.id);await Lr(e.destinationPaths,r,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await oi(e.projectRoot,o),o}async function ck(e){let t=await le(e.projectRoot)??Yn("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=fn(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let n=await we(e.projectRoot,t.native.artifact_root),r=await we(e.projectRoot,i);if($(n.nativeRoot,r.nativeRoot)||$(r.nativeRoot,n.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Me(n.nativeRoot))throw new Error(`Native source root does not exist: ${n.nativeRoot}`);if(await l0(n),await Me(r.nativeRoot))throw new Error(`Native destination is occupied: ${r.nativeRoot}`);let a=await ci(n,"root-move",`move root to ${i}`),o=s0(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=ok({id:o,paths:n,now:e.now??new Date}),l=rk(r,o);try{if(await u0(n,a.file),await Me(l))throw new Error(`Native move staging path is occupied: ${l}`);return await oi(e.projectRoot,fu(t,s)),await xf(n,c),await e.hooks?.afterRootMoveStage?.("copying",c),await sk({projectRoot:e.projectRoot,config:fu(t,s),pending:s,sourcePaths:n,destinationPaths:r,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:n.nativeRoot,toNativeRoot:r.nativeRoot,transactionId:o}}finally{await li(a)}}async function lk(e){let t=await le(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await we(e.projectRoot,i.fromArtifactRoot),r=await we(e.projectRoot,i.toArtifactRoot),a=rk(r,i.id),o=await Me(n.nativeRoot)?n:r,s=await ci(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await S0(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await Me(n.nativeRoot))throw m;let h=ok({id:i.id,paths:n,now:new Date});await xf(n,h),c={journal:h,paths:n}}if(e.strategy==="continue"){let m=await sk({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:n,destinationPaths:r,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:r.nativeRoot,config:m}}if(!await Me(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=ek(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Me(r.nativeRoot)&&await ba(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await hu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:n,target:r.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=ek(a,i.id);!t.native.pending_root_move?.cleanup&&await Me(a)&&await ba(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await hu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:n,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await nt(n,i.id);await Wc(n,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await oi(e.projectRoot,p),{activeNativeRoot:n.nativeRoot,config:p}}finally{await li(s)}}var ds=4096,E0=4096,R0=1024;async function yr(e,t,i){try{let n=await pt({root:e.nativeRoot,directory:t,label:"Native doctor directory",maxEntries:i});return await n.verify(),n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}}async function pu(e,t){let i=new Map(e.map(n=>[Fe.resolve(n.file),{...n,file:Fe.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await ho(r)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:r}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await bf(n,r,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:r});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:r}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:r}),!1)}}return!0}async function C0(e,t){let i=Qb(e),n;try{await A(e.projectRoot,i);let r=await rs(e);if(!r)return[];n=r}catch(r){return r.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${r.message}`,path:i}]}if(n.schema!=="comet.selection.v2"||n.workflow!=="native"||typeof n.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await W(e,n.change),[]}catch(r){if(r.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${r.message}`,path:i}]}return t?(await k0.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${n.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${n.change}`,path:i}]}async function P0(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await A(e.nativeRoot,i)}catch(n){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${n.message}`,path:i})}return t}async function A0(e,t){let i=[],n=[];for(let r of await yr(e,e.transactionsDir,E0)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await nt(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:Fe.join(e.transactionsDir,r.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){n.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Mc([e],`doctor archive recovery ${a.id}`,async()=>await pu([{paths:e,file:Fe.join(e.locksDir,"root-move.lock")},{paths:e,file:Fe.join(e.locksDir,"archive.lock")}],i)?(await rS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){n.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){n.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else n.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:n}}async function x0(e,t,i){let n=[];for(let r of await yr(e,e.locksDir,R0)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=Fe.join(e.locksDir,r.name);try{let o=await ho(a);if(o.status==="active")n.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")n.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await bf(e,a,o);s.status==="removed"?n.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&n.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else n.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){n.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return n}async function T0(e,t,i=5){let n=[],r=t?await ap(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await ap(e,{maxVerifyFailures:i});if(t&&r.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of r){if(a.migrationRequired)continue;if(a.phase==="invalid"){n.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Fe.join(e.changesDir,a.name,$e)});continue}let o=await Ye(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||n.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Fe.join(e.projectRoot,s.path)}:{}})}return n}async function _0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await zr(e,r);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${r} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Mw(e,r);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${r} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${r}: ${a.message}`,path:Fe.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function I0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await Jf(e,r))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${r} uses legacy external-probe or hash-only metadata`,path:Ur(e,r),repair:"migrate"});continue}let a=await W(e,r);await zw({paths:e,name:r,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${r} with process-free root identities`,path:Ur(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:Ur(e,r)})}return i}async function j0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=ss(e,r);try{let o=await cs(e,r),s=await ot(e,r);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${r} requires a newer runtime`,path:Fe.join(e.changesDir,r,$e)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${r}`:`Native change ${r} requires migration to the current schema`,path:o?a:Fe.join(e.changesDir,r,$e),repair:"migrate"});continue}await zS({paths:e,name:r}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${r} to the current schema`,path:Fe.join(e.changesDir,r,$e)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${r}: ${o.message}`,path:a})}}return i}async function O0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await yi(e,r)}catch(o){if(o instanceof zo)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Be(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Mc([e],`doctor transition recovery ${r}`,async()=>await pu([{paths:e,file:Fe.join(e.locksDir,"root-move.lock")},{paths:e,file:Fe.join(e.locksDir,`transition-${r}.lock`)}],i)?(await LN(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:Be(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Be(e,r)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${r}`,path:Be(e,r),repair:"continue"})}}return i}async function $0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Ji(e,r),o;try{o=await zi(e,r)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${r}`,path:a});continue}try{if(!await Mc([e],`doctor checkpoint recovery ${r}`,async()=>await pu([{paths:e,file:Fe.join(e.locksDir,"root-move.lock")},{paths:e,file:Fe.join(e.locksDir,`transition-${r}.lock`)}],i)?(await fb(e,r),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${r}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function uk(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await le(n.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:n.configFile}]}}let a=!!r?.native.pending_root_move;if(r?.native.pending_root_move){let c=r.native.pending_root_move,[l,u]=await Promise.all([we(n.projectRoot,c.fromArtifactRoot),we(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await pu([{paths:l,file:Fe.join(l.locksDir,"root-move.lock")},{paths:u,file:Fe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await lk({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await we(n.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await P0(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await A0(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await j0(n,{name:e.name,repair:t})),i.push(...await I0(n,{name:e.name,repair:t})),i.push(...await _0(n,{name:e.name,repair:t})),i.push(...await O0(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await $0(n,{name:e.name,repair:t})),i.push(...await ZS({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await x0(n,t,s.unfinished)),i.push(...await C0(n,t)),i.push(...await T0(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}async function dk(e,t){let i=ut(e,"--repair"),n=X(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new j("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();G(e);let a=await cS(t),o=await uk({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?ee("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}import H0 from"path";async function fk(e,t){let i=oe(e,"evidence subcommand");if(i==="format"){let n=X(e,"--entries");G(e);let r;if(n)r=await lS(H0.resolve(n),mi);else{if(process.stdin.isTTY)throw new j("evidence format requires acceptance evidence entries JSON on stdin, or --entries <path>");r=await uS(mi)}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=Bl(a);return ee("evidence format",{block:o},`${o}
235
- `)}throw new j(`Unknown evidence command: ${i}`)}import{promises as U0}from"fs";import Sa from"path";var D0=null;function M0(e,t){let i=e;for(let n of t)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function hk(e,t){return(...i)=>{let n=D0;if(n===null)return t(...i);let r=M0(`async:${e}`,i),a=n.entries.get(r);if(a)return a.value;let o=t(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as F0}from"fs";var L0=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),q0=new Set(["glob","grep","listfiles","read","readfile","search","view"]),vk=["file_path","filePath","path","target_file","targetFile"],gk=["file_paths","filePaths","paths","files","targets"],wk=["operations","edits"],B0=["patch","diff","patchText","patch_text","changes"];function mp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pk(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function V0(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function J0(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function z0(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return J0(e[t]);return e}function mk(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of e.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function Nr(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)Nr(e,i);return}if(mp(t)){for(let i of vk)Nr(e,t[i]);for(let i of gk)Nr(e,t[i]);for(let i of wk)Nr(e,t[i])}}function W0(e,t){let i=[],n=[t,e].filter(mp);for(let r of n){for(let a of vk)Nr(i,r[a]);for(let a of gk)Nr(i,r[a]);for(let a of wk)Nr(i,r[a]);for(let a of B0){let o=r[a];typeof o=="string"&&i.push(...mk(o))}}return typeof t=="string"&&i.push(...mk(t)),[...new Set(i)]}function fs(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!mp(i))return{intent:"unknown",targets:[],toolName:null};let n=V0(i),r=W0(i,z0(i));return n&&L0.has(pk(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n}:n&&q0.has(pk(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 yk(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return fs("",e);try{return fs(F0(0,"utf8"),e)}catch{return fs("",e)}}function mu(e,t){let i=Sa.relative(e,t);return i===""||!i.startsWith("..")&&!Sa.isAbsolute(i)}function K0(e,t,i){return i.targets.length>0&&i.targets.every(n=>{let r=Sa.resolve(e,n);return mu(e,r)?Sa.relative(e,r).replaceAll("\\","/")===".comet/config.yaml"||mu(t,r):!0})}async function G0(e){let t=await le(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await we(e,t.native.artifact_root),n;try{n=await U0.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 W(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var Y0=hk("nativeActiveContext",e=>G0(e));async function Nk(){let{intent:e,targets:t}=await yk();return{intent:e,targets:t}}async function bk(e,t,i){let n=await Y0(e);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:K0(e,n.paths.nativeRoot,t)?"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 Zb(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(t.intent==="unknown"||t.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 t.targets){let c=Sa.resolve(e,s);if(!mu(e,c)){o=!0;continue}if(Sa.relative(e,c).replaceAll("\\","/")===".comet/config.yaml"||mu(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}}async function Sk(e,t){let i=X(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new j("--hook-output must be copilot");G(e);let n=await bk(t,await Nk());return i==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{}
228
+ `)}import{createHash as Z$}from"node:crypto";import{constants as ep,promises as Zt}from"node:fs";import mr from"node:path";import{TextDecoder as eH}from"node:util";var hS={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},Se=class extends Error{constructor(i,n){super(n);this.kind=i}kind};function tH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function pS(e){let t=tH(e.scope.baseline),[i,n]=await Promise.all([bt({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),bn(e.paths,t,{origin:"explicit"})]),r=Tn({baseline:t,current:n,contractHash:e.scope.authority.contractHash,declaredArtifacts:e.scope.authority.declaredArtifacts,noCodeReason:e.scope.authority.noCodeReason,...e.scope.authority.gitChangedPaths?{gitChangedPaths:e.scope.authority.gitChangedPaths}:{}});return{contractHash:i.contract.contractHash,snapshotHash:r.scope.currentProjectionHash}}function mS(e,t){let i=(e??(()=>new Date))();if(!(i instanceof Date)||!Number.isFinite(i.getTime()))throw new Error(`Native check ${t} time is invalid`);return i.toISOString()}function iH(e,t,i){let n=[],r=i.scope.contractHash,a=i.scope.currentProjectionHash;return e.contractHash!==r&&n.push("contract-before-does-not-match-scope"),e.snapshotHash!==a&&n.push("implementation-before-does-not-match-scope"),t.contractHash!==e.contractHash&&n.push("contract-changed-during-check"),t.snapshotHash!==e.snapshotHash&&n.push("implementation-changed-during-check"),t.contractHash===e.contractHash&&t.contractHash!==r&&n.push("contract-after-does-not-match-scope"),t.snapshotHash===e.snapshotHash&&t.snapshotHash!==a&&n.push("implementation-after-does-not-match-scope"),n}function nH(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function iu(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function rH(e,t){let i=mr.resolve(e),n=mr.resolve(t);if(!$(i,n))throw new Se("unsafe-file","Scoped file parent escapes the project root");let r=[],a=i;for(let o of["",...mr.relative(i,n).split(mr.sep).filter(Boolean)]){o&&(a=mr.join(a,o));let s;try{s=await Zt.lstat(a)}catch(l){throw l.code==="ENOENT"?new Se("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new Se("unsafe-file","Scoped file parent is not a real directory");let c=await Zt.realpath(a);if(r.length>0&&!$(r[0].realPath,c))throw new Se("unsafe-file","Scoped file parent resolves outside the project");r.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:r[0].realPath,chain:r}}async function vS(e){for(let t of e){let i;try{i=await Zt.lstat(t.path)}catch(n){throw n.code==="ENOENT"?new Se("unsafe-file","Scoped file parent changed while reading"):n}if(!i.isDirectory()||i.isSymbolicLink()||!nH(t,i)||await Zt.realpath(t.path)!==t.realPath)throw new Se("unsafe-file","Scoped file parent changed while reading")}}async function aH(e){let t=mr.resolve(e.projectRoot,...e.file.path.split("/"));if(!$(e.projectRoot,t))throw new Se("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:i,chain:n}=await rH(e.projectRoot,mr.dirname(t)),r;try{r=await Zt.lstat(t)}catch(c){throw c.code==="ENOENT"?new Se("scope-mismatch","Scoped file no longer exists"):c}if(!r.isFile()||r.isSymbolicLink())throw new Se("unsafe-file","Scoped file is not a real regular file");if(r.size!==e.file.expected.size)throw new Se("scope-mismatch","Scoped file size no longer matches its projection");let a=await Zt.realpath(t);if(!$(i,a))throw new Se("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":ep.O_RDONLY|ep.O_NOFOLLOW|ep.O_NONBLOCK,s=await Zt.open(t,o).catch(c=>{throw c.code==="ENOENT"?new Se("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new Se("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),Zt.lstat(t),Zt.realpath(t)]);if(await vS(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!iu(r,c)||!iu(c,l))throw new Se("unsafe-file","Scoped file changed while opening");let d=[],f=Z$("sha256"),p=Buffer.allocUnsafe(64*1024),m=0;for(;;){let N=e.file.expected.size+1-m;if(N<1)throw new Se("scope-mismatch","Scoped file exceeds its projected size");let S=await s.read(p,0,Math.min(p.length,N),null);if(S.bytesRead===0)break;if(m+=S.bytesRead,m>e.file.expected.size)throw new Se("scope-mismatch","Scoped file exceeds its projected size");let R=Buffer.from(p.subarray(0,S.bytesRead));d.push(R),f.update(R)}let[h,v,b]=await Promise.all([s.stat(),Zt.lstat(t),Zt.realpath(t)]);if(await vS(n),m!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new Se("scope-mismatch","Scoped file content no longer matches its projection");if(!h.isFile()||!v.isFile()||v.isSymbolicLink()||b!==a||!$(i,b)||!iu(c,h)||!iu(c,v))throw new Se("unsafe-file","Scoped file changed while reading");let E=Buffer.concat(d,m);if(E.includes(0))return{bytes:m,text:null};try{return{bytes:m,text:new eH("utf-8",{fatal:!0}).decode(E)}}catch{return{bytes:m,text:null}}}finally{await s.close()}}function oH(e){let t=new Map(e.current.entries.map(r=>[r.path,r])),i=[],n=[];for(let r of e.scope.changes){if(!r.after)continue;let a=t.get(r.path);if(!a||a.hash!==r.after.hash||a.size!==r.after.size||a.type!=="file"){n.push(r.path);continue}i.push({path:r.path,expected:r.after})}return i.sort((r,a)=>r.path.localeCompare(a.path,"en")),n.sort((r,a)=>r.localeCompare(a,"en")),{files:i,mismatches:n}}function sH(e,t,i){let n=t.split(`
229
+ `);for(let r=0;r<n.length;r+=1){let a=n[r].endsWith("\r")?n[r].slice(0,-1):n[r],o=r+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&i({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&i({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&i({path:e,line:o,kind:"space-before-tab"})}}async function gS(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await gi(e.paths,e.state.name,e.state.implementation_scope),i=await pS({paths:e.paths,state:e.state,scope:t}),n=mS(e.clock,"start"),r=oH(t),a=[],o=0,s=N=>{o+=1,a.length<Pe.maxIssues&&a.push(N)},c=r.files,l=r.files.length+r.mismatches.length;if(t.scope.unresolvedScopes.some(N=>N.kind==="scope-detail-overflow")){let N=t.scope.changes.at(-1)?.path??t.current.entries.at(-1)?.path??t.baseline.entries.at(-1)?.path;if(!N)throw new Error("Native implementation scope overflow has no bounded diagnostic path");s({path:N,line:1,kind:"scan-limit"}),c=[]}else if(l>Pe.maxFiles){let N=[...r.files.map(S=>S.path),...r.mismatches].sort((S,R)=>S.localeCompare(R,"en"));s({path:N[Pe.maxFiles],line:1,kind:"scan-limit"}),c=[]}else{let N=0;for(let S of r.files){if(S.expected.size>Pe.maxFileBytes){s({path:S.path,line:1,kind:"scan-limit"}),c=[];break}if(N+=S.expected.size,N>Pe.maxTotalBytes){s({path:S.path,line:1,kind:"scan-limit"}),c=[];break}}}for(let N of r.mismatches)s({path:N,line:1,kind:"scope-mismatch"});let d=0,f=0,p=0;for(let N of c)try{let S=await aH({projectRoot:e.paths.projectRoot,file:N});p+=S.bytes,S.text===null?(f+=1,s({path:N.path,line:1,kind:"binary-skipped"})):(d+=1,sH(N.path,S.text,s))}catch(S){if(!(S instanceof Se))throw S;s({path:N.path,line:1,kind:S.kind})}let m=await pS({paths:e.paths,state:e.state,scope:t}),h=mS(e.clock,"end"),v=iH(i,m,t);a.sort((N,S)=>N.path.localeCompare(S.path,"en")||N.line-S.line||hS[N.kind]-hS[S.kind]);let b=Yy({change:e.state.name,sourceRevision:e.state.revision,status:o===0&&v.length===0?"passed":"failed",startedAt:n,endedAt:h,contract:{expectedHash:t.scope.contractHash,beforeHash:i.contractHash,afterHash:m.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:i.snapshotHash,afterSnapshotHash:m.snapshotHash},counts:{filesSelected:l,filesScanned:d,binaryFilesSkipped:f,bytesScanned:p,issueCount:o,recordedIssueCount:a.length},issues:a,issuesTruncated:o>a.length,stale:v.length>0,staleReasons:v}),E=await vb({paths:e.paths,name:e.state.name,receipt:b});return{receipt:Li(b),ref:E}}async function wS(e){return re(e.paths,`check ${e.name}`,()=>He(e.paths,e.name,`check ${e.name}`,()=>tp(e)))}async function tp(e){await St(e.paths,e.name);let t=await W(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native check requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native check requires an implementation scope");let i=await gS({paths:e.paths,state:t}),n=await Sb({paths:e.paths,state:t,checkReceipt:i.receipt,checkReceiptRef:i.ref});return{change:t,receipt:i.receipt,checkRef:i.ref,ref:n.ref}}async function yS(e,t){let i=oe(e,"change name");G(e);let{paths:n}=await _e(t),r=await wS({paths:n,name:i}),a={ref:r.ref,hash:r.receipt.receiptHash,status:r.receipt.status,checker:r.receipt.checker,counts:r.receipt.counts,issues:r.receipt.issues,issuesTruncated:r.receipt.issuesTruncated,stale:r.receipt.stale,staleReasons:r.receipt.staleReasons,startedAt:r.receipt.startedAt,endedAt:r.receipt.endedAt,sourceRevision:r.receipt.sourceRevision},o=r.receipt.status==="passed"&&!r.receipt.stale;return{command:"check",exitCode:o?0:1,data:a,text:`Native check ${o?"passed":"failed"}: ${r.ref}
230
+ `}}import HS from"path";import{promises as wH}from"fs";import cH from"path";function ip(e,t){return cH.resolve(e,...t.split(/[\\/]/u))}async function nu(e,t){let i=[],n=C(e,t.name),r=ip(n,at.stateRef),a;try{a=await ye(n)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:r}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:r}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:r}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:r}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:r}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:r});let o=ip(n,a.trajectoryRef),s=await zr(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await qe(n,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=ip(n,a.checkpointRef);try{let u=await Jr(n,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}import os from"path";var NS=8,lH={"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function uH(e){let t=lH[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:Wr(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function dH(e,t,i){if(!i.path)return null;let n;if(os.isAbsolute(i.path)?n=os.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=os.resolve(C(e,t.name),...i.path.split(/[\\/]/u)):n=os.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!$(e.projectRoot,n))return null;let r=os.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function fH(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function ei(e){return e.findings.map(t=>{let i=uH(t.code);return{code:t.code,message:t.message,severity:i.severity,path:dH(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:fH(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let n={error:0,warning:1,info:2};return n[t.severity]-n[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function bS(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,NS),truncated:t.length>NS}}import SS from"path";var kS=240,ES=8,ru=50;function RS(e){let t=Array.from(e);return t.length<=kS?e:`${t.slice(0,kS-1).join("")}…`}function hH(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function pH(e){let t=[...new Set(e.map(hH))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,ES),reasonCount:e.length,codesTruncated:t.length>ES};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,ru),reasonsTruncated:e.length>ru}}}async function CS(e){let t=null;try{let s=await zi(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Ji(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Ji(e.paths,e.state.name)}}let i=await ub({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=pH(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Xt.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:RS(i.checkpoint.summary),nextAction:RS(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:SS.relative(e.paths.projectRoot,SS.join(C(e.paths,e.state.name),...i.checkpoint.manifestRef.split("/"))).replaceAll("\\","/"),artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Xt.maxArtifacts}}function mH(e){if(e.phase!=="build"||e.verification_result!=="fail"||!e.implementation_scope||!e.verification_evidence)throw new Error("Native repair guard requires a failed Verify-to-Build state")}async function PS(e,t){let i=C(e,t.name),n=await ye(i);if(!n||!t.run_id||n.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let r=await Jr(i,n.checkpointRef);if(!r||r.runId!==n.runId||r.stateVersion!==n.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await qe(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function np(e,t){let i=await PS(e,t);return{committed:i,latest:RN(i),history:EN(i)}}function vH(e,t){let i=e.latest;if(!i)return null;let n=e.history.filter(l=>l.kind==="failure"),r=n.length===0?0:Vo({signatureHash:i.signatureHash,...i.contractHash===null?{}:{failedAcceptanceIds:i.failedAcceptanceIds,failedCheckIds:i.failedCheckIds}},n.slice(0,-1)),a=i.overrideSummaryHash!==null,o=e.history.some(l=>l.kind==="override"&&l.signatureHash===i.signatureHash),s=n.length>=t,c=i.disposition==="hard-stop"&&!s?"continue":i.disposition;return{disposition:s?"hard-stop":c,reasonCode:a?"override-accepted":o&&i.disposition==="manual-stop"?"override-already-used":s?"repair-iteration-limit":i.disposition==="manual-stop"?"repeated-failure-stop":i.disposition==="warn"?"repeated-failure-warning":"new-failure-signature",signatureHash:i.signatureHash,consecutiveFailures:r,totalRepairFailures:n.length,remainingIterations:Math.max(0,t-n.length),overrideAccepted:a}}async function AS(e,t,i){return vH(await np(e,t),i)}function xS(e){return{disposition:e.decision.disposition,reasonCode:e.decision.reasonCode,signatureHash:e.decision.signature.signatureHash,consecutiveFailures:e.decision.consecutiveFailures,totalRepairFailures:e.decision.totalRepairFailures,remainingIterations:e.decision.remainingIterations,overrideAccepted:e.decision.overrideAccepted}}function gH(e){return sa(e.filter(t=>t.status!=="passed").map(t=>Zy(t)))}async function TS(e){if(!e.state.implementation_scope)throw new Error("Native repair failure has no implementation scope");let t=[...new Set([...e.envelope.requiredReceiptRefs,...e.envelope.receiptRefs])],[i,n,r]=await Promise.all([PS(e.paths,e.state),gi(e.paths,e.state.name,e.state.implementation_scope),Promise.all(t.map(o=>oa(e.paths,e.state.name,o)))]),a=gH(r);return PN({...i,envelope:e.envelope,implementationScope:n,maxVerifyFailures:e.maxVerifyFailures,...a.length>0?{failedCheckIds:a}:{}})}async function _S(e){let t=await np(e.paths,e.state),i=t.latest,n=Wt(e.currentImplementationScope).scope.contractHash;if(i?.contractHash!==null&&i?.contractHash!==n){if(e.override)throw new Error("Native repair override cannot cross a confirmed contract change");return{disposition:"proceed",eventProjection:null}}let r=t.history.filter(u=>u.kind==="failure").length;if(i&&r>=e.maxVerifyFailures){if(e.override)throw new Error("Native repair hard stop cannot be overridden");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash)}}let a=i?.disposition==="hard-stop"&&r<e.maxVerifyFailures?"continue":i?.disposition;if(!i||a!=="manual-stop"&&a!=="hard-stop"){if(e.override)throw new Error("Native repair override requires the latest manual stop");return{disposition:"proceed",eventProjection:null}}let o=t.history.some(u=>u.kind==="override"&&u.signatureHash===i.signatureHash);if(!(e.state.phase==="build"&&e.state.verification_result==="fail"&&e.state.implementation_scope!==null&&e.state.verification_evidence!==null)){if(e.override)throw new Error("Native repair override requires an active failed Verify-to-Build state");return{disposition:"proceed",eventProjection:null}}mH(e.state);let[c,l]=await Promise.all([On(e.paths,e.state.name,e.state.verification_evidence),gi(e.paths,e.state.name,e.state.implementation_scope)]);if(l.scope.scopeHash!==c.implementationScopeHash)throw new Error("Native repair verification evidence does not match its implementation scope");if(i.contractHash===null&&la(e.currentImplementationScope)!==la(l)){if(e.override)throw new Error("Native repair override is not valid after implementation scope progress");return{disposition:"proceed",eventProjection:null}}if(i.disposition==="hard-stop"){if(e.override)throw new Error("Native repair hard stop cannot be overridden without implementation progress");return{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}}return o?{disposition:"hard-stop",signatureHash:i.signatureHash,overrideRecorded:o}:e.override?{disposition:"proceed",eventProjection:CN({...t.committed,override:e.override}).eventProjection}:{disposition:"manual-stop",signatureHash:i.signatureHash,overrideRecorded:!1}}async function IS(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await np(e,t),r=n.latest;if(!r)return null;let a=n.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=r.disposition==="hard-stop"&&!o?"continue":r.disposition;return{disposition:o?"hard-stop":s,signatureHash:r.signatureHash,overrideRecorded:n.history.some(c=>c.kind==="override"&&c.signatureHash===r.signatureHash),failedAcceptanceIds:[...r.failedAcceptanceIds],failedCheckIds:[...r.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var yH=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,ga=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function NH(e){try{return(await rs(e))?.change??null}catch{return null}}function bH(e,t,i=!1,n){return e.phase==="archive"?t?`comet native archive ${e.name} --dry-run`:i?`comet native next ${e.name} --summary "<summary>"`:null:`comet native next ${e.name} --summary "<summary>"${e.phase==="shape"||e.phase==="build"&&e.approval!=="confirmed"?" --confirmed":""}`}async function SH(e,t){let i=C(e,t.name),n=[...(await ir(i,t.brief)).findings,...(await Xr(e,t)).findings,...await nu(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await hi(e,t.name);if(r===null)n.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Nn(e,r);a.complete||n.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(r){n.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${r.message}`})}if(t.phase==="build")try{let r=await bt({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==r.contract.contractHash&&n.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(r){n.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${r.message}`})}try{await yi(e,t.name)&&n.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(r){n.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${r.message}`})}return t.verification_report?n.push(...(await Yr(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&n.push({code:"verification-report-missing",message:"Native change has no verification report"}),n}async function Ye(e,t,i){let n=await NH(e)===t,r;try{let y=await ot(e,t);if(y.status==="migration-required"&&y.state)return{name:t,phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,schema:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};r=y.state}catch(y){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:n,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,error:y.message}}let a=await CS({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await IS(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let y=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:y,message:`Native repair is stopped at failure signature: ${o.signatureHash}`})}}catch{s.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let c;if(i?.details&&(r.phase==="build"||r.phase==="verify"||r.phase==="archive"))try{let y=await bt({changeDir:C(e,r.name),briefRef:r.brief,specChanges:r.spec_changes}),g=new Map;if(r.phase==="build"&&r.verification_result==="fail"&&r.verification_evidence){let k=await On(e,r.name,r.verification_evidence);for(let x of k.acceptanceTrace.entries)g.set(x.acceptanceId,x.status==="failed"?"failed":x.status==="missing"?"missing":"satisfied")}c=Ll({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:g,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(y){if(i.acceptanceCursor)throw y;c=void 0}let l=[];try{let y=await Tl(e,r.name);l.push(...y.findingCodes.map(g=>({code:g,message:`Native change overlap is visible in the current root: ${g}`})))}catch{l.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let u=[];try{let y=await ul(e,r.name);if(y){let g=await Ww({paths:e,identity:y});u.push(...g.findingCodes.map(k=>({code:k,message:`Native workspace advisory changed: ${k} (${g.driftComponents.join(", ")||"no-component"})`})))}}catch{u.push({code:"workspace-inspection-unavailable",message:"Native workspace advisory could not be recomputed safely"})}let d=[],f=!1;if(r.phase==="verify"){let y=await es({paths:e,state:r});f=y.freshness!=="fresh",d.push(...y.findingCodes.map(g=>({code:g,message:`Native Verify implementation scope is not current: ${g}`})))}let p=null,m=[];if(r.phase==="archive")try{p=await hr({paths:e,name:r.name}),m.push(...p.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let h=[...await SH(e,r),...a.findings,...l,...u,...d,...s,...m].filter((y,g,k)=>k.findIndex(x=>x.code===y.code&&x.path===y.path)===g),v=ei({paths:e,state:r,findings:h}),b=v.filter(y=>!Wr(y.code)),E=r.phase==="archive"&&p?.ready===!0&&b.length===0,N=f||r.phase==="archive"&&(p?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),S=v.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",w=v.find(y=>y.severity==="error");return{name:r.name,phase:r.phase,revision:r.revision,approval:r.approval,verificationResult:r.verification_result,specChanges:r.spec_changes.length,selected:n,nextCommand:S||R?null:bH(r,E,N,i?.clarificationMode),archiveReady:E,inspection:a.inspection,findingSummary:bS(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:De({state:r,findings:v,archiveReady:E,evidenceRetreat:N,clarificationMode:i?.clarificationMode}),repair:o,...i?.details?{...c?{acceptancePage:c}:{},findings:v.slice(0,50),inspectionDetails:a.inspectionDetails,checkpointDetails:a.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:ru,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...w?{error:w.message}:{}}}async function kH(e){let t;try{t=await ui({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await wH.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>ga.maxChanges))throw new Error(`Native status exceeds ${ga.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function jS(e,t){let i=t.toString(36),n=H("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function EH(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=yH.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let n=H("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==n)throw new Error("Native status cursor integrity check failed");return i}async function rp(e,t){let i=await kH(e),n=H("comet.native.status-names.v1",i),r=EH({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+ga.maxItems).map(c=>Ye(e,c,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let c of a){let l=[...o,c],u=r+l.length,d={schema:"comet.native.status-page.v1",total:i.length,offset:r,items:l,nextCursor:u<i.length?jS(n,u):null,limits:{...ga}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ga.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(c)}let s=r+o.length;return{schema:"comet.native.status-page.v1",total:i.length,offset:r,items:o,nextCursor:s<i.length?jS(n,s):null,limits:{...ga}}}async function ap(e,t){return(await rp(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{randomUUID as RH}from"crypto";function OS(e,t){let i=Ne(e).trim();if(i.length===0||i.length>2e3)throw new Error(`${t} must be between 1 and 2000 characters`);return i}function CH(e){if(e!==void 0){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native expected revision must be a positive integer");return e}}async function $S(e){let t=OS(e.summary,"Checkpoint summary"),i=OS(e.nextAction,"Checkpoint next action"),n=CH(e.expectedRevision);return re(e.paths,`checkpoint ${e.name}`,()=>He(e.paths,e.name,`checkpoint ${e.name}`,async()=>{await St(e.paths,e.name);let r=await W(e.paths,e.name),a=await sb(e.paths,e.name,e.artifacts??[]),o=Yo(a),s=F(JSON.stringify({summary:t,nextAction:i,artifacts:a.artifacts})),c=await $h(e.paths,e.name);if(c?.inputHash===s&&c.stateRevision===r.revision&&c.phase===r.phase){if(n!==void 0&&n!==c.previousRevision&&n!==r.revision)throw new Cn(r.name,n,r.revision);return{change:r,checkpoint:c,idempotent:!0,expectedRevision:n??c.previousRevision,previousRevision:c.previousRevision,revision:r.revision,outcome:"idempotent",continuation:De({state:r})}}if(n!==void 0&&r.revision!==n)throw new Cn(r.name,n,r.revision);let l={...r,revision:r.revision+1},u={schema:"comet.native.progress-checkpoint.v1",id:e.checkpointId?.()??RH(),change:r.name,phase:r.phase,previousRevision:r.revision,stateRevision:l.revision,summary:t,nextAction:i,inputHash:s,manifestHash:o,manifestRef:Ih(o),artifactCount:a.artifacts.length,createdAt:(e.now??new Date).toISOString()},d=await db({paths:e.paths,previousState:r,nextState:l,checkpoint:u,manifest:a,now:e.now,checkpointId:()=>u.id});await e.hooks?.afterPrepared?.(d);let f=await Xo(e.paths,e.name,e.hooks);if(!f)throw new Error("Native checkpoint journal disappeared before completion");return{change:f.nextState,checkpoint:f.checkpoint,idempotent:!1,expectedRevision:n??f.checkpoint.previousRevision,previousRevision:f.checkpoint.previousRevision,revision:f.nextState.revision,outcome:"recorded",continuation:De({state:f.nextState})}}))}async function DS(e,t){let i=oe(e,"change name"),n=X(e,"--summary");if(!n)throw new j("--summary is required");let r=X(e,"--next-action");if(!r)throw new j("--next-action is required");let a=Ki(e,"--artifact"),o=oS(e);G(e);let{config:s,paths:c}=await _e(t),l=await $S({paths:c,name:i,summary:n,nextAction:r,artifacts:a,expectedRevision:o}),u=await Ye(c,i,{clarificationMode:s.native.clarification_mode,maxVerifyFailures:s.native.max_verify_failures}),d=HS.relative(c.projectRoot,HS.join(C(c,i),...l.checkpoint.manifestRef.split("/"))).replaceAll("\\","/");return ee("checkpoint",{...l,checkpoint:{...l.checkpoint,manifestRef:d},continuation:u.continuation})}import{promises as E0}from"fs";import Fe from"path";import{createHash as zH,randomUUID as WH}from"node:crypto";import{constants as up,promises as ie}from"node:fs";import he from"node:path";var su=Nu(mc(),1);import{randomUUID as PH}from"crypto";import{promises as BS}from"fs";import sp from"path";import{isDeepStrictEqual as cp}from"util";var vr=/^[a-f0-9]{64}$/u,AH=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),xH=new Set(["sourceHash","targetHash","nextJournal"]),TH=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),MS=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),_H=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function au(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function FS(e){return JSON.stringify(e,null,2)+`
231
+ `}function lp(e){return e.schema===Oe?dl(e):Rn(e)}function op(e,t){return{...e,schema:Oe,minimum_runtime_version:2,revision:t}}function IH(e){return{...e,schema:Ii,minimum_runtime_version:2,revision:1,previousState:op(e.previousState,1),nextState:op(e.nextState,2)}}function ou(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ce,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function jH(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:_i,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:ou(e.previousState),nextState:{...ou(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:ct.definition.metadata.version,skillHash:cr}:e.nextRun}}function LS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function wa(e,t){return JSON.stringify(dl(e))===JSON.stringify(dl(t))}function qS(e,t){return JSON.stringify(Rn(e))===JSON.stringify(Rn(t))}function Gi(e,t){return cp(e,t)}function OH(e,t,i,n){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let r=e;if(au(r,TH,"Schema migration transition supersede plan"),typeof r.sourceHash!="string"||!vr.test(r.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof r.transitionId!="string"||r.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof r.evidenceHash!="string"||!vr.test(r.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=kn(r.previousRun),o=kn(r.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Gi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!r.eventData||typeof r.eventData!="object"||Array.isArray(r.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=r.eventData,u=Object.keys(l);if(u.length!==MS.size||u.some(f=>!MS.has(f))||l.fromSchema!==Oe||l.toSchema!==Ce||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==r.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:r.transitionId,migrationId:n,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(r.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:r.sourceHash,transitionId:r.transitionId,previousRun:a,nextRun:o,evidenceHash:r.evidenceHash,eventData:l}}function ss(e,t){return sp.join(C(e,t),"runtime","schema-migration.json")}function $H(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");au(e,AH,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let n=i.fromSchema===Tt&&i.toSchema===Oe,r=i.fromSchema===Oe&&i.toSchema===Ce;if(!n&&!r)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!vr.test(i.sourceHash)||typeof i.targetHash!="string"||!vr.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=n?Pn(i.nextState):_t(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,su.stringify)(lp(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");au(i.transition,xH,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!vr.test(l.sourceHash)||typeof l.targetHash!="string"||!vr.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=n?bh(l.nextJournal,t):Fl(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+`
232
+ `)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===Oe?wa(a,u.previousState)||wa(a,u.nextState):a.schema===Ce&&(qS(a,u.previousState)||qS(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(n&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!r||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ce)throw new Error("Schema migration transition supersede target schema is invalid");s=OH(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!r||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");au(i.runRetreat,_H,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=kn(l.previousRun),d=kn(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!vr.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ce||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function cs(e,t){let i=ss(e,t);await A(e.nativeRoot,i);try{let n=await Lc({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return $H(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function HH(e,t,i){let n=await hi(e,t),r=n?await Nn(e,n):await bo(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=el(r),o=r.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=r.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new pi(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await tl(e,t,r)}async function VS(e){try{return await rt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function DH(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function JS(e,t){let i=t.transitionSupersede,n=C(e,t.change),r=await qe(n,i.nextRun.trajectoryRef),a=r.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!cp(o.event,DH(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:r.length,sequence:o?.event.sequence??null}}async function MH(e,t,i){if(!t.transitionSupersede)return;let n=Be(e,t.change),r=await VS(n);if(r===t.transitionSupersede.sourceHash)return;if(r!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${r}`);let a=await ye(C(e,t.change)),o=await JS(e,t),s=await Jr(C(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!Gi(a,t.transitionSupersede.nextRun)||o.sequence===null||!s||s.runId!==t.transitionSupersede.nextRun.runId||s.stateVersion!==t.transitionSupersede.nextRun.iteration||s.trajectoryOffset!==o.sequence||s.contextHash!==null||s.artifactsHash!==F(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function FH(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=C(e,t.change),a=await ye(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Gi(a,n.nextRun)){if(!Gi(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Zn(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!Gi(await ye(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await JS(e,t);if(o.sequence===null){let l=await Hn({changeDir:r,run:n.nextRun,type:"state_migrated",data:{...n.eventData,migrationId:t.id,evidenceHash:n.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await lr({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Be(e,t.change),c=await VS(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await BS.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function LH(e,t,i){if(!t.runRetreat)return;let n=C(e,t.change),r=await ye(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Gi(r,t.runRetreat.nextRun)){if(!Gi(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Zn(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await qe(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Hn({changeDir:n,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await lr({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function qH(e,t,i){let n=await cs(e,t);if(!n)return null;if(await Kr(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=sp.join(C(e,t),$e),a=await rt(r);if(await MH(e,n,a===n.targetHash),await HH(e,t,n.createdAt),a!==n.targetHash){if(a!==n.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${n.sourceHash}, actual ${a}`);await je(r,(0,su.stringify)(lp(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=Be(e,t),s=await rt(o);if(s!==n.transition.targetHash){if(s!==n.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${n.transition.sourceHash}, actual ${s}`);await de(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await FH(e,n,i),await LH(e,n,i),await BS.rm(ss(e,t),{force:!0}),n.nextState}async function BH(e){let t=C(e.paths,e.state.name),i=await ye(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let n={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},r=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:Oe,toSchema:Ce,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function VH(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let r=wa(i,t.previousState),a=wa(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=C(e.paths,i.name),s=await ye(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Gi(s,t.previousRun),l=Gi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await qe(o,t.nextRun.trajectoryRef)).map((b,E)=>({event:b,index:E})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!cp(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...ou(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await rt(Be(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:h,evidenceHash:v,eventData:{fromSchema:Oe,toSchema:Ce,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function JH(e){let t,i,n,r;if(e.state.schema===Tt){if(t=op(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==er)throw new Error("Native v1 change has a transition from another schema generation");let s=IH(e.pendingTransition.journal);if(LS(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(LS(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Be(e.paths,e.name);i={sourceHash:await rt(c),targetHash:F(FS(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ii)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await VH({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=jH(s);if(wa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(wa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Be(e.paths,e.name);i={sourceHash:await rt(u),targetHash:F(FS(l)),nextJournal:l}}}else t=ou(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await BH({paths:e.paths,state:e.state,migrationId:e.id}));let a=sp.join(C(e.paths,e.name),$e),o=(0,su.stringify)(lp(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Tt?Oe:Ce,sourceHash:await rt(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function zS(e){return re(e.paths,`migrate schema for ${e.name}`,()=>He(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await qH(e.paths,e.name,e.hooks);if(i?.schema===Ce)return i;let n=await ot(e.paths,e.name);if(n.status==="current"&&n.state)return n.state;if(n.status!=="migration-required"||!n.state)throw new Error(n.message??`Native change ${e.name} cannot be migrated`);if(await Kr(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=n.state;if(r.schema!==Tt&&r.schema!==Oe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Sh(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await JH({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??PH()}),s=ss(e.paths,e.name);await A(e.paths.nativeRoot,s),await de(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Yi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),UH=512*1024,gr=/^([a-f0-9]{64})\.json$/u,KH=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,GH=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,cu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function fp(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ri(e,t){return fp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function YS(e,t){return fp(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function ya(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ze(e,t){return e<t?-1:e>t?1:0}function YH(e,t){let i=he.relative(e.projectRoot,t);if(i.length===0||he.isAbsolute(i)||i===".."||i.startsWith(`..${he.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(he.sep).join("/")}function XS(e,t){return he.join(C(e,t),"runtime","evidence")}function lu(e,t){return YH(e,XS(e,t))}async function uu(e,t){let i=he.resolve(e),n=he.resolve(t);if(!$(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=he.relative(i,n).split(he.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=he.join(o,s));let c=await ie.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await ie.realpath(o);if(a.length>0&&!$(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...ya(c)})}return a}async function Ht(e){for(let t of e){let i=await ie.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!fp(t,i)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function QS(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:wt(e,t)}function WS(e){return e!==null&&GH.test(e)?[e]:[]}function XH(e,t,i,n){if(e==="snapshots")return{canonical:ea(i,t),dependencies:[]};if(e==="scopes"){let a=ta(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Fo(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[wt("scopes",a.scopeHash)]}}if(e==="verifications"){let a=na(i);if(a.change!==n||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(WS));return{canonical:a,dependencies:[a.implementationScopeRef,aN(a.reportHash),...WS(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||zH("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=Bo(i);if(a.bindings.change!==n||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let r=Li(i);if(r.change!==n||r.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:r,dependencies:[]}}async function Ln(e){let t=await ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?UH:Gt;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await ie.realpath(e.file);if(!$(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":up.O_RDONLY|up.O_NOFOLLOW|up.O_NONBLOCK,a=await ie.open(e.file,r).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Ht(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!Ri(ya(t),o)||!Ri(ya(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let E=i+1-d,N=await a.read(u,0,Math.min(u.length,E),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,N.bytesRead)))}let[f,p,m]=await Promise.all([a.stat(),ie.lstat(e.file),ie.realpath(e.file)]);if(await Ht(e.directoryChain),!p.isFile()||p.isSymbolicLink()||m!==n||!Ri(ya(o),f)||!Ri(ya(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(h)}catch(E){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:E})}let b=XH(e.kind,e.hash,v,e.name);if(h!==JSON.stringify(b.canonical,null,2)+`
233
+ `)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:ya(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(Ze)}}finally{await a.close()}}async function US(e){try{return await ie.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function QH(e){let t=C(e.paths,e.name),i=XS(e.paths,e.name);await A(e.paths.nativeRoot,i);let n;try{let o=await uu(t,i);n=await ie.readdir(i,{withFileTypes:!0}),await Ht(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of cu){if(!n.some(d=>d.name===o))continue;let s=he.join(i,o),c=await uu(t,s),l=(await ie.readdir(s,{withFileTypes:!0})).sort((d,f)=>Ze(d.name,f.name)),u=new Map;for(let d of l){let f=KH.exec(d.name);if(!f)continue;let p=u.get(f[1])??[];p.push(d),u.set(f[1],p)}for(let[d,f]of[...u.entries()].sort(([p],[m])=>Ze(p,m))){if(f.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${o}/${d}`);let p=f[0];if(!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${o}/${p.name}`);let m=he.join(s,d),h=gr.exec(d)?.[1];if(!h)throw new Error(`Native evidence cleanup quarantine name is invalid: ${p.name}`);let v=QS(o,h),b=he.join(s,p.name),E=await Ln({changeRoot:t,file:b,ref:v,kind:o,hash:h,name:e.name,directoryChain:c}),N=await US(m),S=N?null:await Ln({changeRoot:t,file:m,ref:v,kind:o,hash:h,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:b,document:E,action:N?"restore-original":"finish-linked-recovery",originalDocument:S})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(Ze);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Na(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${du(a)}`),path:lu(e.paths,e.name)}]};for(let o of r.sort((s,c)=>Ze(s.ref,c.ref))){if(await Ht(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Ln({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Ln({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!Ri(o.originalDocument.identity,u.identity)||!Ri(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await ie.rm(o.quarantine),await Ht(o.document.directoryChain);continue}if(!await US(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await ie.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!Ri(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await ie.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Ln({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Ln({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:gr.exec(he.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!YS(o.document.identity,c.identity)||!Ri(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await ie.rm(o.quarantine),await Ht(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Na(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${du(a)}`),path:lu(e.paths,e.name)}]}}async function ZH(e,t){let i=C(e,t),n=he.join(i,"runtime","evidence");await A(e.nativeRoot,n);let r;try{let c=await uu(i,n);r=await ie.readdir(n,{withFileTypes:!0}),await Ht(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!cu.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(Ze);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${du(a)}`);let o=[],s=0;for(let c of cu){if(!r.some(f=>f.name===c))continue;let l=he.join(n,c),u=await uu(i,l),d=(await ie.readdir(l,{withFileTypes:!0})).sort((f,p)=>Ze(f.name,p.name));await Ht(u);for(let f of d){if(o.length>=Yi.maxDocuments)throw new Error(`Native evidence store exceeds ${Yi.maxDocuments} documents`);let p=gr.exec(f.name);if(!p||!f.isFile()||f.isSymbolicLink())throw new Error(`Native evidence kind ${c} has an unknown or special entry: ${f.name}`);let m=QS(c,p[1]),h=he.join(l,f.name);await A(e.nativeRoot,h);let v=await Ln({changeRoot:i,file:h,ref:m,kind:c,hash:p[1],name:t,directoryChain:u});if(s+=v.size,s>Yi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Yi.maxScannedBytes} scanned bytes`);o.push(v)}await Ht(u)}return o}function KS(e,t){let i=new Set,n=[...e].sort(Ze).reverse();for(;n.length>0;){let r=n.pop();if(i.has(r))continue;let a=t.get(r);if(!a)throw new Error(`Native evidence dependency is missing: ${r}`);i.add(r);for(let o of[...a.dependencies].sort(Ze).reverse())i.has(o)||n.push(o)}return i}function e0(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let n=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(Ze),r=[];for(;n.length>0;){let a=n.shift(),o=t.get(a);r.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(n.push(s),n.sort(Ze))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function t0(e,t,i){let n=new Map(e.map(c=>[c.ref,c]));if(n.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!n.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let r=KS(t,n),a=new Set(r);for(let c of e)i-c.mtimeMs<Yi.minimumAgeMs&&a.add(c.ref);for(let c of cu){let l=e.filter(u=>u.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Ze(u.ref,d.ref)).slice(0,Yi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=KS(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Yi.minimumAgeMs).sort((c,l)=>Ze(c.ref,l.ref));return{candidates:e0(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function du(e){let t=e.slice(0,Yi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Na(e){let t=Yi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function dp(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(Ze);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Na(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${du(r)}`),path:n}}async function GS(e,t){try{await ie.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await ie.rename(e,t)}catch{}}async function i0(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ht(e.directoryChain);let i=await Ln({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:gr.exec(he.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await ie.lstat(e.file),r=await ie.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!Ri(e.identity,n)||!Ri(e.identity,i.identity)||!$(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=he.join(he.dirname(e.file),`.${he.basename(e.file)}.${WH()}.gc`);await ie.rename(e.file,a);try{let[o,s]=await Promise.all([ie.lstat(a),ie.realpath(a)]);if(await Ht(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!YS(e.identity,o)||!$(e.directoryChain[0].realPath,s))throw await GS(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await ie.rm(a),await Ht(e.directoryChain)}catch(o){throw await GS(a,e.file),o}}async function n0(e){if((await le(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await ie.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())return!0;try{let r=await nt(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function r0(e,t){if(t)return[t];let i;try{i=await ie.readdir(e.changesDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort(Ze)}async function a0(e,t){let i=await ot(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([yi(e,t),cs(e,t),zi(e,t)]);return n!==null||r!==null||a!==null}async function o0(e){if(await a0(e.paths,e.name))return[];let t=await ot(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await QH({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let n=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&n.push(c);let r=await ZH(e.paths,e.name),a=t0(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=lu(e.paths,e.name);if(!e.repair)return[...i.findings,dp(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await i0(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[dp(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Na(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,dp(e.name,a,!0,o)]}async function ZS(e){if(e.deferAll||await n0(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async r=>{let a=[];for(let o of await r0(e.paths,e.name))try{a.push(...await o0({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Na(`Native evidence retention refused to clean ${o}: ${s.message}`),path:lu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let n=await i(!1);if(n.some(r=>r.severity==="error")||!n.some(r=>r.code==="evidence-retention-candidates"||r.code==="evidence-retention-recovery-required"))return n;try{return await re(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Na(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as s0,randomUUID as c0}from"crypto";import{promises as wr}from"fs";import ae from"path";var pp=64*1024*1024,l0=256*1024,nk=16*1024*1024;async function Me(e){try{return await wr.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function u0(e){let t;try{t=await wr.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t){if(!i.isDirectory()||i.isSymbolicLink())continue;let n;try{n=await nt(e,i.name)}catch(r){throw r.code==="ENOENT"?new Error(`Native transaction ${i.name} has no journal; run doctor before moving`,{cause:r}):r}if(n.status!=="committed"&&n.status!=="rolled-back")throw new Error(`Native transaction ${n.id} is unfinished; recover it before moving`)}}async function d0(e,t){for(let i of await wr.readdir(e.locksDir,{withFileTypes:!0})){let n=ae.join(e.locksDir,i.name);if(ae.resolve(n)!==ae.resolve(t)&&(i.isFile()||i.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${n}`)}}async function f0(e){let t;try{t=await wr.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((n,r)=>n.name.localeCompare(r.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let n;try{n=await ot(e,i.name)}catch{continue}n.status!=="current"||!n.state||!("revision"in n.state)||await Ao({paths:e,name:i.name,revision:n.state.revision})}}async function us(e,t){let i=[];async function n(r){let a=await pt({root:e,directory:r,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(r,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await wr.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await ue({root:e,file:c,maxBytes:pp,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await n(e),i.sort((r,a)=>r.ref.localeCompare(a.ref))}async function h0(e,t,i,n){await di({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await pt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await wr.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await di({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ai({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:pp,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await r(e,t)}async function ba(e,t,i,n){let r=await us(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await us(t,{rejectSymlinks:!0,excludedFiles:n?new Set([ae.resolve(n)]):void 0});if(JSON.stringify(r)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function rk(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function p0(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function m0(e){return`${e}.removing`}function ek(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function ak(e,t,i){return ae.join(zc(e,t).directory,`root-move-cleanup-${i}.json`)}function v0(e){return JSON.stringify(e,null,2)+`
234
+ `}function g0(e){return s0("sha256").update(e).digest("hex")}function w0(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,n=Object.keys(i).sort(),r=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function y0(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let n=e;if(JSON.stringify(Object.keys(n).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||n.schema!=="comet.native.root-move-cleanup.v1"||n.transactionId!==t||n.kind!==i||!Array.isArray(n.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let r=n.entries.map(w0);for(let a=0;a<r.length;a+=1){if(a>0&&r[a-1].ref.localeCompare(r[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(r[a].ref);if(o!=="."&&!r.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:r}}async function N0(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=v0(t);if(Buffer.byteLength(i,"utf8")>nk)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await je(ak(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),g0(i)}async function b0(e){let t=await ue({root:e.paths.nativeRoot,file:ak(e.paths,e.id,e.cleanup.kind),maxBytes:nk,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return y0(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function hp(e){let t=await us(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(n=>[n.ref,n]));for(let n of t){let r=i.get(n.ref);if(!r||JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${n.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function tk(e){return e.ref.split("/").length}async function S0(e){let i=[...await hp({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>tk(a)-tk(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=ae.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await qc({root:e.projectRoot,file:a,maxBytes:pp,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await Sf({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${r.ref}`}),n+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,r.ref,n)}await hp({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Sf({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function fu(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function ok(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function k0(e,t,i,n){for(let a of[e,t])try{let o=await nt(a,n);if(o.kind!=="root-move")throw new Error(`Transaction ${n} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let r=ae.join(i,"runtime","transactions",n,"transaction.json");try{let a=await ue({root:i,file:r,maxBytes:l0,label:`Staged Native root-move journal ${n}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${n}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${n}`,{cause:a})}}async function ik(e){let t=fu(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await oi(e.projectRoot,t),t}async function ls(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=fu(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await oi(e.projectRoot,i),i}async function hu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let n=i.cleanup;if(n&&n.kind!==e.kind)throw new Error(`Native root move has unfinished ${n.kind} cleanup; cannot start ${e.kind}`);let r=await Me(e.target),a=await Me(e.quarantine);if(r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!n){if(!r&&!a)return t;if(!r&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await N0({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await us(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await ls({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await b0({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await Me(e.target),a=await Me(e.quarantine),r&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(r){if(n.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Bg({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(n.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return ls({projectRoot:e.projectRoot,config:t,id:e.id})}return await hp({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await ls({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await ls({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await S0({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),ls({projectRoot:e.projectRoot,config:t,id:e.id})}async function sk(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await Me(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=m0(e.staging);t=await hu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await us(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await h0(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await ba(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await ik({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await Me(e.destinationPaths.nativeRoot)){if(await Me(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await ba(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Me(e.staging))throw new Error("Native move staging tree is missing");await ba(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await wr.rename(e.staging,e.destinationPaths.nativeRoot)}t=await ik({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await Me(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=p0(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Me(e.sourcePaths.nativeRoot)&&await ba(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await hu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:n,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await f0(e.destinationPaths);let r=await nt(e.destinationPaths,e.pending.id);await Lr(e.destinationPaths,r,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await oi(e.projectRoot,o),o}async function ck(e){let t=await le(e.projectRoot)??Yn("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let i=fn(e.toArtifactRoot);if(i===t.native.artifact_root)throw new Error(`Native artifact root is already ${i}`);let n=await we(e.projectRoot,t.native.artifact_root),r=await we(e.projectRoot,i);if($(n.nativeRoot,r.nativeRoot)||$(r.nativeRoot,n.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Me(n.nativeRoot))throw new Error(`Native source root does not exist: ${n.nativeRoot}`);if(await u0(n),await Me(r.nativeRoot))throw new Error(`Native destination is occupied: ${r.nativeRoot}`);let a=await ci(n,"root-move",`move root to ${i}`),o=c0(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:i,stage:"copying"},c=ok({id:o,paths:n,now:e.now??new Date}),l=rk(r,o);try{if(await d0(n,a.file),await Me(l))throw new Error(`Native move staging path is occupied: ${l}`);return await oi(e.projectRoot,fu(t,s)),await xf(n,c),await e.hooks?.afterRootMoveStage?.("copying",c),await sk({projectRoot:e.projectRoot,config:fu(t,s),pending:s,sourcePaths:n,destinationPaths:r,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:n.nativeRoot,toNativeRoot:r.nativeRoot,transactionId:o}}finally{await li(a)}}async function lk(e){let t=await le(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await we(e.projectRoot,i.fromArtifactRoot),r=await we(e.projectRoot,i.toArtifactRoot),a=rk(r,i.id),o=await Me(n.nativeRoot)?n:r,s=await ci(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await k0(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await Me(n.nativeRoot))throw m;let h=ok({id:i.id,paths:n,now:new Date});await xf(n,h),c={journal:h,paths:n}}if(e.strategy==="continue"){let m=await sk({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:n,destinationPaths:r,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:r.nativeRoot,config:m}}if(!await Me(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=ek(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await Me(r.nativeRoot)&&await ba(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await hu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:n,target:r.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=ek(a,i.id);!t.native.pending_root_move?.cleanup&&await Me(a)&&await ba(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await hu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:n,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await nt(n,i.id);await Wc(n,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await oi(e.projectRoot,p),{activeNativeRoot:n.nativeRoot,config:p}}finally{await li(s)}}var ds=4096,R0=4096,C0=1024;async function yr(e,t,i){try{let n=await pt({root:e.nativeRoot,directory:t,label:"Native doctor directory",maxEntries:i});return await n.verify(),n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}}async function pu(e,t){let i=new Map(e.map(n=>[Fe.resolve(n.file),{...n,file:Fe.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await ho(r)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:r}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await bf(n,r,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:r});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:r}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:r}),!1)}}return!0}async function P0(e,t){let i=Qb(e),n;try{await A(e.projectRoot,i);let r=await rs(e);if(!r)return[];n=r}catch(r){return r.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${r.message}`,path:i}]}if(n.schema!=="comet.selection.v2"||n.workflow!=="native"||typeof n.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await W(e,n.change),[]}catch(r){if(r.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${r.message}`,path:i}]}return t?(await E0.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${n.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${n.change}`,path:i}]}async function A0(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await A(e.nativeRoot,i)}catch(n){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${n.message}`,path:i})}return t}async function x0(e,t){let i=[],n=[];for(let r of await yr(e,e.transactionsDir,R0)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await nt(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:Fe.join(e.transactionsDir,r.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){n.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Mc([e],`doctor archive recovery ${a.id}`,async()=>await pu([{paths:e,file:Fe.join(e.locksDir,"root-move.lock")},{paths:e,file:Fe.join(e.locksDir,"archive.lock")}],i)?(await rS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){n.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){n.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else n.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:n}}async function T0(e,t,i){let n=[];for(let r of await yr(e,e.locksDir,C0)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=Fe.join(e.locksDir,r.name);try{let o=await ho(a);if(o.status==="active")n.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")n.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await bf(e,a,o);s.status==="removed"?n.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&n.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else n.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){n.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return n}async function _0(e,t,i=5){let n=[],r=t?await ap(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await ap(e,{maxVerifyFailures:i});if(t&&r.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of r){if(a.migrationRequired)continue;if(a.phase==="invalid"){n.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Fe.join(e.changesDir,a.name,$e)});continue}let o=await Ye(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||n.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Fe.join(e.projectRoot,s.path)}:{}})}return n}async function I0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await zr(e,r);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${r} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await Mw(e,r);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${r} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${r}: ${a.message}`,path:Fe.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function j0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await Jf(e,r))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${r} uses legacy external-probe or hash-only metadata`,path:Ur(e,r),repair:"migrate"});continue}let a=await W(e,r);await zw({paths:e,name:r,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${r} with process-free root identities`,path:Ur(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:Ur(e,r)})}return i}async function O0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=ss(e,r);try{let o=await cs(e,r),s=await ot(e,r);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${r} requires a newer runtime`,path:Fe.join(e.changesDir,r,$e)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${r}`:`Native change ${r} requires migration to the current schema`,path:o?a:Fe.join(e.changesDir,r,$e),repair:"migrate"});continue}await zS({paths:e,name:r}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${r} to the current schema`,path:Fe.join(e.changesDir,r,$e)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${r}: ${o.message}`,path:a})}}return i}async function $0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await yi(e,r)}catch(o){if(o instanceof zo)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Be(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Mc([e],`doctor transition recovery ${r}`,async()=>await pu([{paths:e,file:Fe.join(e.locksDir,"root-move.lock")},{paths:e,file:Fe.join(e.locksDir,`transition-${r}.lock`)}],i)?(await LN(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:Be(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Be(e,r)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${r}`,path:Be(e,r),repair:"continue"})}}return i}async function H0(e,t){let i=[],n=t.name?[t.name]:(await yr(e,e.changesDir,ds)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Ji(e,r),o;try{o=await zi(e,r)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${r}`,path:a});continue}try{if(!await Mc([e],`doctor checkpoint recovery ${r}`,async()=>await pu([{paths:e,file:Fe.join(e.locksDir,"root-move.lock")},{paths:e,file:Fe.join(e.locksDir,`transition-${r}.lock`)}],i)?(await fb(e,r),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${r}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function uk(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await le(n.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:n.configFile}]}}let a=!!r?.native.pending_root_move;if(r?.native.pending_root_move){let c=r.native.pending_root_move,[l,u]=await Promise.all([we(n.projectRoot,c.fromArtifactRoot),we(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await pu([{paths:l,file:Fe.join(l.locksDir,"root-move.lock")},{paths:u,file:Fe.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await lk({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await we(n.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await A0(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await x0(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await O0(n,{name:e.name,repair:t})),i.push(...await j0(n,{name:e.name,repair:t})),i.push(...await I0(n,{name:e.name,repair:t})),i.push(...await $0(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await H0(n,{name:e.name,repair:t})),i.push(...await ZS({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await T0(n,t,s.unfinished)),i.push(...await P0(n,t)),i.push(...await _0(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}async function dk(e,t){let i=ut(e,"--repair"),n=X(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new j("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();G(e);let a=await cS(t),o=await uk({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?ee("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}import D0 from"path";async function fk(e,t){let i=oe(e,"evidence subcommand");if(i==="format"){let n=X(e,"--entries");G(e);let r;if(n)r=await lS(D0.resolve(n),mi);else{if(process.stdin.isTTY)throw new j("evidence format requires acceptance evidence entries JSON on stdin, or --entries <path>");r=await uS(mi)}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=Bl(a);return ee("evidence format",{block:o},`${o}
235
+ `)}throw new j(`Unknown evidence command: ${i}`)}import{promises as K0}from"fs";import Sa from"path";var M0=null;function F0(e,t){let i=e;for(let n of t)i+="\0"+(typeof n=="string"?n:JSON.stringify(n));return i}function hk(e,t){return(...i)=>{let n=M0;if(n===null)return t(...i);let r=F0(`async:${e}`,i),a=n.entries.get(r);if(a)return a.value;let o=t(...i).catch(s=>{throw n.entries.delete(r),s});return n.entries.set(r,{value:o}),o}}import{readFileSync as L0}from"fs";var q0=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),B0=new Set(["glob","grep","listfiles","read","readfile","search","view"]),vk=["file_path","filePath","path","target_file","targetFile"],gk=["file_paths","filePaths","paths","files","targets"],wk=["operations","edits"],V0=["patch","diff","patchText","patch_text","changes"];function mp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pk(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function J0(e){for(let t of["tool_name","toolName","tool","name"]){let i=e[t];if(typeof i=="string"&&i.trim())return i.trim()}return null}function z0(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function W0(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return z0(e[t]);return e}function mk(e){let t=[],i=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of i)for(let r of e.matchAll(n)){let a=r[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function Nr(e,t){if(typeof t=="string"){let i=t.trim();i&&e.push(i);return}if(Array.isArray(t)){for(let i of t)Nr(e,i);return}if(mp(t)){for(let i of vk)Nr(e,t[i]);for(let i of gk)Nr(e,t[i]);for(let i of wk)Nr(e,t[i])}}function U0(e,t){let i=[],n=[t,e].filter(mp);for(let r of n){for(let a of vk)Nr(i,r[a]);for(let a of gk)Nr(i,r[a]);for(let a of wk)Nr(i,r[a]);for(let a of V0){let o=r[a];typeof o=="string"&&i.push(...mk(o))}}return typeof t=="string"&&i.push(...mk(t)),[...new Set(i)]}function fs(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let i;try{i=JSON.parse(e)}catch{return{intent:"unknown",targets:[],toolName:null}}if(!mp(i))return{intent:"unknown",targets:[],toolName:null};let n=J0(i),r=U0(i,W0(i));return n&&q0.has(pk(n))?{intent:r.length>0?"write":"unknown",targets:r,toolName:n}:n&&B0.has(pk(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 yk(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return fs("",e);try{return fs(L0(0,"utf8"),e)}catch{return fs("",e)}}function mu(e,t){let i=Sa.relative(e,t);return i===""||!i.startsWith("..")&&!Sa.isAbsolute(i)}function G0(e,t,i){return i.targets.length>0&&i.targets.every(n=>{let r=Sa.resolve(e,n);return mu(e,r)?Sa.relative(e,r).replaceAll("\\","/")===".comet/config.yaml"||mu(t,r):!0})}async function Y0(e){let t=await le(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let i=await we(e,t.native.artifact_root),n;try{n=await K0.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 W(i,a.name);o.archived||r.push(o)}return{paths:i,changes:r}}var X0=hk("nativeActiveContext",e=>Y0(e));async function Nk(){let{intent:e,targets:t}=await yk();return{intent:e,targets:t}}async function bk(e,t,i){let n=await X0(e);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:G0(e,n.paths.nativeRoot,t)?"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 Zb(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(t.intent==="unknown"||t.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 t.targets){let c=Sa.resolve(e,s);if(!mu(e,c)){o=!0;continue}if(Sa.relative(e,c).replaceAll("\\","/")===".comet/config.yaml"||mu(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}}async function Sk(e,t){let i=X(e,"--hook-output");if(i!==void 0&&i!=="copilot")throw new j("--hook-output must be copilot");G(e);let n=await bk(t,await Nk());return i==="copilot"?{command:"hook-guard",exitCode:0,data:n,text:n.allowed?`{}
236
236
  `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:n.reason})}
237
237
  `}:n.allowed?{command:"hook-guard",exitCode:0,data:n}:{command:"hook-guard",exitCode:2,data:n,error:{code:"blocked",message:n.reason}}}async function kk(e,t){let i=X(e,"--root"),n=await le(t),r=tu(e,n?.native.language??"en");if(G(e),n?.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let a=fn(i??n?.native.artifact_root??"docs");if(n&&i&&n.native.artifact_root!==a)throw new Error(`Configured Native artifact root is ${n.native.artifact_root}; refusing conflicting root ${a}`);let o=n?{...n,native:{...n.native,language:r}}:Yn(a,r),s=await we(t,o.native.artifact_root);return await _c(s),await oi(t,o),ee("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:r},`Initialized Comet Native at ${s.nativeRoot}
238
238
  `)}async function Ek(e,t){let i=oe(e,"change name"),n=await le(t),r=tu(e,n?.native.language??"en");G(e);let a=n===null;if(n||(n=Yn("docs",r)),n.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);a&&await oi(t,n);let o=await we(t,n.native.artifact_root);await _c(o);let s=await Qw({paths:o,name:i,language:r});await eu(o,s.name);let c=await Ye(o,s.name,{clarificationMode:n.native.clarification_mode,maxVerifyFailures:n.native.max_verify_failures});return ee("new",{...s,continuation:c.continuation},`Created Native change ${s.name}
239
- `)}import{randomUUID as uD}from"crypto";import{promises as X0}from"fs";import Rk from"path";function Q0(e){return{valid:e.length===0,findings:e}}async function Z0(e,t){let i=[];if((t.noCodeReason??"").trim().length>0)return i;if(!t.artifacts||t.artifacts.length===0)return[{code:"build-evidence-missing",message:"Build requires an artifact reference or an explicit no-code reason"}];for(let n of t.artifacts){if(Rk.isAbsolute(n)||n.split(/[\\/]/u).includes("..")||/^(?:[A-Za-z]:|~|[\\/])/u.test(n)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}let r=Rk.resolve(e.projectRoot,...n.split(/[\\/]/u));if(!$(e.projectRoot,r)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}try{await X0.access(r)}catch{i.push({code:"build-artifact-missing",message:`Build artifact does not exist: ${n}`,path:n})}}return i}async function Ck(e){let t=[],i=C(e.paths,e.state.name);if(e.evidence.summary.trim().length===0&&t.push({code:"transition-summary-missing",message:"Phase transition requires a summary"}),e.evidence.confirmed&&e.state.phase!=="shape"&&e.state.phase!=="build"&&t.push({code:"confirmation-not-shape",message:"Explicit confirmation is only valid while leaving Shape or Build"}),t.push(...await nu(e.paths,e.state)),e.state.phase==="shape"||e.state.phase==="build"){let n=await hi(e.paths,e.state.name);if(n===null)t.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let r=await Nn(e.paths,n);r.complete||t.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${r.omittedCount} omitted entries); resolve the omissions before advancing`})}}if(e.state.phase==="shape"){let n=await ir(i,e.state.brief),r=await Xr(e.paths,e.state);t.push(...n.findings,...r.findings),t.length===0&&!e.evidence.confirmed&&t.push({code:"shape-confirmation-required",message:"Native clarification requires explicit user confirmation of the shared understanding before Build"})}else if(e.state.phase==="build")t.push(...(await ir(i,e.state.brief)).findings,...(await Xr(e.paths,e.state)).findings),t.push(...await Z0(e.paths,e.evidence)),t.length===0&&e.state.approval!=="confirmed"&&!e.evidence.confirmed&&t.push({code:"approval-confirmation-required",message:"Native approval is implicit; confirm the current shared understanding before leaving Build"});else if(e.state.phase==="verify"){let n=e.evidence.verificationReport??e.state.verification_report;n?t.push(...(await Yr(i,n)).findings):t.push({code:"verification-report-missing",message:"Verify requires a report path"}),e.evidence.verificationResult||t.push({code:"verification-result-missing",message:"Verify requires pass or fail"}),t.push(...(await Xr(e.paths,e.state)).findings)}else t.push({code:"archive-command-required",message:"Use comet native archive for the Archive phase"});return Q0(t)}import{promises as vp}from"node:fs";import gp from"node:path";var Ak={maxDeclaredArtifacts:128,maxArtifactPathBytes:512};function Pk(e,t){if(e.omitted.some(i=>i.reason==="git-selection-changed"))throw new Error(`Native Git selection changed while capturing the ${t}; stabilize the Git index and retry Build evidence`);if(e.omitted.some(i=>i.reason==="physical-enumeration-limit"||i.reason==="physical-selection-changed"))throw new Error(`Native physical selection was incomplete or changed while capturing the ${t}; retry Build evidence with a stable bounded project tree`)}function eD(e,t){let i=t.omitted.slice(0,20).map(a=>a.path),n=t.omitted.reduce((a,o)=>(a[o.reason]=(a[o.reason]??0)+1,a),{}),r=t.omissionOverflow?.count??0;return r>0&&(n.overflow=r),new pi(e,t.omittedCount,n,i,t.omitted.length>i.length||r>0)}function tD(e,t,i){let n=new Set(i.entries.map(a=>a.path)),r=t.entries.filter(a=>!n.has(a.path)).slice(0,20).map(a=>a.path);return new pi(e,i.omittedCount,{"manifest-size":i.omittedCount},r,i.omittedCount>r.length)}function iD(e,t){let i=e.replaceAll("\\","/").trim();if(i.length===0||i!==e.replaceAll("\\","/")||gp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(i)||i.split("/").includes("..")||gp.posix.normalize(i)!==i||i==="."||i.endsWith("/")||Buffer.byteLength(i,"utf8")>Ak.maxArtifactPathBytes||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127}))throw new Error(`${t} must be a normalized project-relative path`);return i}function nD(e,t){return e.entries.some(i=>i.path===t)?"file":e.entries.some(i=>i.path.startsWith(`${t}/`))?"directory":null}async function rD(e,t,i){let n=iD(i,"Native build artifact"),r=Za(e,n);if(r)throw new Error(`Native build artifact is excluded as ${r}: ${n}`);let a=gp.resolve(e.projectRoot,...n.split("/"));if(!$(e.projectRoot,a))throw new Error(`Native build artifact escapes the project: ${n}`);await A(e.projectRoot,a);try{let o=await vp.lstat(a);if(o.isSymbolicLink())throw new Error(`Native build artifact must not be a symlink or junction: ${n}`);let s=await vp.realpath(a),c=await vp.realpath(e.projectRoot);if(!$(c,s))throw new Error(`Native build artifact resolves outside the project: ${n}`);if(o.isFile())return{path:n,kind:"file"};if(o.isDirectory())return{path:n,kind:"directory"};throw new Error(`Native build artifact is not a file or directory: ${n}`)}catch(o){if(o.code!=="ENOENT")throw o;let s=nD(t,n);if(s===null)throw new Error(`Native build artifact does not exist: ${n}`,{cause:o});return{path:n,kind:s}}}async function aD(e){if(e.refs.length>Ak.maxDeclaredArtifacts)throw new Error("Native build evidence exceeds its declared-artifact budget");let t=await Promise.all(e.refs.map(i=>rD(e.paths,e.baseline,i)));if(t.sort((i,n)=>i.path.localeCompare(n.path)||i.kind.localeCompare(n.kind)),new Set(t.map(i=>i.path)).size!==t.length)throw new Error("Native build evidence contains duplicate or conflicting artifacts");return t}function oD(e){return e.map(t=>({code:"verification-scope-partial",message:`${t.id}: ${t.reason}`,...t.path===null?{}:{path:t.path}}))}function sD(e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error("Native partial allowance requires a scope hash");return e}async function xk(e){if(e.state.phase!=="build")throw new Error(`Native build evidence requires Build, got ${e.state.phase}`);if((e.noCodeReason??"").trim().length>0&&e.artifactRefs.length>0)throw new Error("Native build evidence cannot combine artifacts with a no-code reason");let t=await hi(e.paths,e.state.name);if(t===null)throw new Error("Native change has no baseline content snapshot");let i=await Nn(e.paths,t);if(Pk(i,"baseline projection"),!i.complete)throw eD(e.state.name,i);let n=await bt({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await aD({paths:e.paths,baseline:i,refs:e.artifactRefs}),a=await bn(e.paths,i,{origin:"explicit",now:e.now});Pk(a,"current snapshot");let o=Tn({baseline:i,current:a,contractHash:n.contract.contractHash,declaredArtifacts:r,noCodeReason:e.noCodeReason??null});if(!o.baseline.complete)throw tD(e.state.name,i,o.baseline);let s=wt("scopes",o.scope.scopeHash);if(o.scope.complete){if(e.allowPartialScopeHash!==void 0&&e.allowPartialScopeHash!==null||e.partialReason!==void 0&&e.partialReason!==null)throw new Error("Complete Native build evidence must not include a partial allowance");return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:[],unresolvedScopes:[]}}if(e.allowPartialScopeHash===void 0||e.allowPartialScopeHash===null)return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:oD(o.scope.unresolvedScopes),unresolvedScopes:o.scope.unresolvedScopes};if(!e.confirmed)throw new Error("Native partial verification requires explicit confirmation");if(sD(e.allowPartialScopeHash)!==o.scope.scopeHash)throw new Error("Native partial allowance does not match the current implementation scope");let l=Fy({change:e.state.name,scopeBundle:o,allowedScopeIds:o.scope.unresolvedScopes.map(d=>d.id),reason:e.partialReason??"",confirmedSummary:e.confirmedSummary??"",sourceRevision:e.state.revision,now:e.now}),u=wt("allowances",l.allowanceHash);return{contract:n,bundle:o,scopeRef:s,allowance:l,allowanceRef:u,findings:[],unresolvedScopes:o.scope.unresolvedScopes}}async function vu(e){if(await dN({paths:e.paths,name:e.state.name,bundle:e.preparation.bundle})!==e.preparation.scopeRef)throw new Error("Native implementation scope persistence ref changed");if(e.includeAllowance===!1||e.preparation.allowance===null)return;if(await fN({paths:e.paths,name:e.state.name,allowance:e.preparation.allowance})!==e.preparation.allowanceRef)throw new Error("Native partial allowance persistence ref changed")}import{promises as Tk}from"fs";import _k from"path";var Ik=Yt.maxSpecs*4;async function gu(e){try{return await rt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wu(e,t){let i=_k.join(C(e,t),"specs"),n;try{n=await ui({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await Tk.opendir(i);try{for await(let s of o){if(a+=1,a>Ik)throw new Error(`Native proposed specs directory exceeds ${Ik} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Vt(s.name);let c=_k.join(i,s.name,"spec.md");await A(e.nativeRoot,c);let l;try{l=await Tk.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>Yt.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function jk(e,t){let i=new Map(t.spec_changes.map(a=>[a.capability,a])),n=await wu(e,t.name),r=[];for(let a of n){let o=i.get(a);if(o?.operation==="remove")throw new Error(`Capability ${a} has both a proposed spec and a remove intent`);if(o){r.push({...o,source:`specs/${a}/spec.md`});continue}let s=Jt(e,a);await A(e.nativeRoot,s);let c=await gu(s);r.push({capability:a,operation:c===null?"create":"replace",source:`specs/${a}/spec.md`,base_hash:c})}for(let a of t.spec_changes)a.operation==="remove"&&!n.includes(a.capability)&&r.push(a);return r.sort((a,o)=>a.capability.localeCompare(o.capability))}async function cD(e,t){let i=await wu(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Jt(e,r);await A(e.nativeRoot,o);let s=await gu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Jt(e,r.capability);await A(e.nativeRoot,a);let o=await gu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function Ok(e){Vt(e.name);let t=Ne(e.summary);return $n(t,"Spec rebase summary"),re(e.paths,`rebase specs for ${e.name}`,()=>He(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await St(e.paths,e.name);let i=await W(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=C(e.paths,e.name),r=await ye(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await cD(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=F(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await Wo({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await Ni(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function $k(e,t,i){return Vt(t),Vt(i),re(e,`remove spec ${i} from ${t}`,()=>He(e,t,`remove spec ${i} from ${t}`,async()=>(await St(e,t),lD(e,t,i))))}async function lD(e,t,i){let n=await W(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await wu(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Jt(e,i);await A(e.nativeRoot,o);let s=await gu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await Gr(e,c,n.revision),c}async function Hk(e,t){let i=C(e,t),n={},r=0;for(let a of await wu(e,t)){let o=await ge({root:i,ref:`specs/${a}/spec.md`,maxBytes:Yt.maxFileBytes});if(r+=o.size,r>Yt.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");n[a]=o.text}return n}function dD(e){return`Native verification receipt binding is invalid: ${e.detail}. Re-issue the affected receipts with \`comet native receipt refresh ${e.change} --apply\`.`}function Mk(e){return e.confirmed!==void 0||e.artifacts!==void 0||e.noCodeReason!==void 0||e.allowPartialScopeHash!==void 0||e.partialReason!==void 0||e.verificationResult!==void 0||e.verificationReport!==void 0||e.repairOverrideSignature!==void 0||e.repairOverrideSummary!==void 0}function wp(e){return e.reasonCode==="override-already-used"?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${e.signatureHash}`}:e.disposition==="warn"?{code:"repair-stagnation-warning",message:`Native repair repeated the same failure signature: ${e.signatureHash}`}:e.disposition==="manual-stop"?{code:"repair-stagnation-stop",message:`Native repair stopped after repeated failure signature: ${e.signatureHash}`}:{code:"repair-iteration-limit",message:`Native repair reached its total iteration limit at signature: ${e.signatureHash}`}}function fD(e){if($n(e.summary,"Native transition summary"),e.noCodeReason!==void 0&&$n(e.noCodeReason,"Native transition no-code reason"),e.repairOverrideSignature!==void 0&&!/^[a-f0-9]{64}$/u.test(e.repairOverrideSignature))throw new Error("Native repair override signature must be a SHA-256 hash");e.repairOverrideSummary!==void 0&&jl(e.repairOverrideSummary)}function hD(e){return{...e,summary:Ne(e.summary),...e.noCodeReason===void 0?{}:{noCodeReason:Ne(e.noCodeReason)},...e.partialReason===void 0?{}:{partialReason:Ne(e.partialReason)},...e.repairOverrideSummary===void 0?{}:{repairOverrideSummary:Ne(e.repairOverrideSummary)}}}function pD(e,t){let i=t.repairOverrideSignature!==void 0,n=t.repairOverrideSummary!==void 0;if(i!==n)throw new Error("Native repair override signature and summary must be provided together");if((i||n)&&e.phase!=="build")throw new Error("Native repair override is only valid while leaving Build")}async function Dk(e){if(Mk(e.transition.evidence))throw new Error("Native evidence retreat only accepts a transition summary");let t=e.state.phase;if(t!=="verify"&&t!=="archive"||e.run.currentStep!==t||e.run.pending!==null)throw new Error("Native Verify/Archive Run cannot retreat evidence safely");if(t==="archive"?["complete","partial"].includes((await fr({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness):(await es({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness==="fresh"){let c=ei({paths:e.transition.paths,state:e.state,findings:[t==="archive"?{code:"archive-command-required",message:"Current verification evidence is fresh; use Native Archive preview"}:{code:"verification-result-missing",message:"Current implementation scope is fresh; complete Verify with a result and report"}]});return{change:e.state,previousPhase:t,next:"manual",nextCommand:t==="archive"?`comet native archive ${e.state.name} --dry-run`:null,findings:c,continuation:De({state:e.state,archiveReady:t==="archive",clarificationMode:e.transition.clarificationMode})}}let n={...e.state,revision:e.state.revision+1,phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},r={...e.run,currentStep:"build",iteration:e.run.iteration+1,pending:null,status:"running"},a={previousPhase:t,nextPhase:"build",evidenceHash:e.evidenceHash,summary:e.transition.evidence.summary,artifacts:[],noCodeReason:null,verificationResult:null},o=await Wo({paths:e.transition.paths,previousState:e.state,nextState:n,previousRun:e.run,nextRun:r,evidenceHash:e.evidenceHash,eventData:a,operation:"evidence-retreat",now:e.transition.now,transitionId:e.transition.transitionId});await e.transition.hooks?.afterPrepared?.(o);let s=await Ni(e.transition.paths,e.state.name,e.transition.hooks);if(!s)throw new Error("Native evidence retreat journal disappeared before completion");return{change:s,previousPhase:t,next:"auto",nextCommand:null,findings:[],continuation:De({state:s,clarificationMode:e.transition.clarificationMode})}}async function Fk(e){let t={...e,maxVerifyFailures:e.maxVerifyFailures??Tg,evidence:hD(e.evidence)};return fD(t.evidence),re(e.paths,`advance ${e.name}`,()=>He(e.paths,e.name,`advance ${e.name}`,()=>mD(t)))}async function mD(e){await St(e.paths,e.name);let t=await W(e.paths,e.name),i=t.phase,n=C(e.paths,e.name),r=Hl(e.evidence),a=await ye(n);if(a){let x=(await qe(n,a.trajectoryRef)).at(-1);if(x?.type==="state_transitioned"&&x.data.evidenceHash===r&&x.data.nextPhase===t.phase&&(x.data.previousPhase==="verify"?["complete","partial"].includes((await fr({paths:e.paths,state:t,now:e.now})).freshness):!0)){let D=Object.hasOwn(x.data,"repairStagnation")?await AS(e.paths,t,e.maxVerifyFailures):null,z=D&&D.disposition!=="continue"?ei({paths:e.paths,state:t,findings:[wp(D)]}):[],ne=D?.disposition==="manual-stop"||D?.disposition==="hard-stop";return{change:t,previousPhase:x.data.previousPhase??t.phase,next:ne?"manual":"auto",nextCommand:ne?null:t.phase==="archive"?`comet native archive ${t.name} --dry-run`:null,findings:z,continuation:De({state:t,findings:z,archiveReady:t.phase==="archive"&&t.verification_result==="pass",clarificationMode:e.clarificationMode}),...D?{repair:D}:{}}}}if(t.phase==="archive"){if(!a)throw new Error("Native Archive Run state is missing");return Dk({transition:e,state:t,run:a,evidenceHash:r})}if(t.phase==="verify"&&!Mk(e.evidence)){if(!a)throw new Error("Native Verify Run state is missing");if((await es({paths:e.paths,state:t,now:e.now})).freshness!=="fresh")return Dk({transition:e,state:t,run:a,evidenceHash:r})}let o={...t,spec_changes:await jk(e.paths,t)};pD(t,e.evidence);let s=await Ck({paths:e.paths,state:o,evidence:e.evidence,clarificationMode:e.clarificationMode});if(!s.valid){let k=ei({paths:e.paths,state:t,findings:s.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode})}}let c=t.phase==="shape"?await bt({changeDir:n,briefRef:o.brief,specChanges:o.spec_changes}):null;if(t.phase!=="build"&&(e.evidence.allowPartialScopeHash!==void 0||e.evidence.partialReason!==void 0))throw new Error("Native partial scope allowance is only valid while leaving Build");let l=t.phase==="build"?await xk({paths:e.paths,state:o,artifactRefs:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,allowPartialScopeHash:e.evidence.allowPartialScopeHash??null,partialReason:e.evidence.partialReason??null,confirmedSummary:e.evidence.summary,confirmed:e.evidence.confirmed??!1,now:e.now}):null;if(l&&(t.approved_contract_hash??null)!==l.contract.contract.contractHash&&!e.evidence.confirmed){let k=ei({paths:e.paths,state:t,findings:[{code:"contract-changed-after-approval",message:"Native contract changed after approval; re-confirm the current contract before leaving Build"}]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode})}}let u=l?{scopeHash:l.bundle.scope.scopeHash,scopeRef:l.scopeRef,complete:l.bundle.scope.complete,unresolvedScopeCount:l.unresolvedScopes.length,partialAllowanceRef:l.allowanceRef,acceptancePage:Ll({criteria:l.contract.contract.acceptance,acceptanceHash:l.contract.contract.acceptanceHash})}:void 0;if(l&&l.findings.length>0){await vu({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let k=ei({paths:e.paths,state:t,findings:l.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode}),preparedScope:u}}let d=null,f=l?la(l.bundle):null;if(t.phase==="build"&&l){let k=await _S({paths:e.paths,state:t,currentImplementationScope:l.bundle,maxVerifyFailures:e.maxVerifyFailures,...e.evidence.repairOverrideSignature&&e.evidence.repairOverrideSummary?{override:{expectedSignatureHash:e.evidence.repairOverrideSignature,summary:e.evidence.repairOverrideSummary}}:{}});if(k.disposition!=="proceed"){await vu({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let x=ei({paths:e.paths,state:t,findings:[k.disposition==="hard-stop"&&k.overrideRecorded?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${k.signatureHash}`}:wp({disposition:k.disposition,reasonCode:k.disposition==="hard-stop"?"repair-iteration-limit":"repeated-failure-stop",signatureHash:k.signatureHash})]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:x,continuation:De({state:t,findings:x,clarificationMode:e.clarificationMode}),preparedScope:u&&{...u,partialAllowanceRef:null}}}d=k.eventProjection}let p=t.phase==="verify"&&e.evidence.verificationResult==="pass"?(await tp({paths:e.paths,name:t.name})).ref:null,m=t.phase==="verify"?await xb({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:p,now:e.now}):null;if(m&&!m.ready){let k=ei({paths:e.paths,state:t,findings:m.findingCodes.map(x=>{if(x==="verification-receipt-binding-mismatch"&&m.receiptBindingFailures&&m.receiptBindingFailures.length>0){let U=m.receiptBindingFailures.map(D=>`${D.acceptanceId?`${D.ref}[${D.acceptanceId}]`:D.ref} -> ${D.mismatches.join("; ")}`).join(" | ");return{code:x,message:dD({change:t.name,detail:U})}}return{code:x,message:`Native verification evidence is not current: ${x}`}})});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode})}}let h=null;if(t.phase==="verify"&&e.evidence.verificationResult==="fail"&&m?.ready&&m.envelope){let k=await TS({paths:e.paths,state:t,envelope:m.envelope,maxVerifyFailures:e.maxVerifyFailures});d=k.eventProjection,f=k.facts.implementationScopeHash,h=xS(k)}let v=a;if(!v){if(t.run_id!==null||t.phase!=="shape")throw new Error("Native Run state is missing or inconsistent");v=Iw(ct,e.runId?.()??uD(),cr)}if(v.currentStep!==t.phase)throw new Error(`Native Run step ${v.currentStep??"(none)"} does not match ${t.phase}`);let b=ms(ct,v,new Set,ua,void 0);if(!b.action)throw new Error(b.reason??"Native runtime produced no action");let E=vs(ct,b.state,{actionId:b.action.id,status:"succeeded",summary:e.evidence.summary,state:e.evidence.verificationResult?{verification_result:e.evidence.verificationResult}:void 0},ua,void 0);if(!E.currentStep)throw new Error("Archive completion must use the archive command");let N={...o,revision:t.revision+1,phase:E.currentStep,approval:e.evidence.confirmed?"confirmed":t.approval,approved_contract_hash:t.phase==="shape"?c.contract.contractHash:t.phase==="build"&&e.evidence.confirmed?l.contract.contract.contractHash:t.approved_contract_hash??null,run_id:v.runId,...t.phase==="build"?{verification_result:"pending",verification_report:null,implementation_scope:l.scopeRef,partial_allowance:l.allowanceRef,verification_evidence:null}:{},...t.phase==="verify"?{verification_result:e.evidence.verificationResult,verification_report:m.envelope.reportRef,verification_evidence:m.evidenceRef}:{}},S={previousPhase:i,nextPhase:N.phase,evidenceHash:r,summary:e.evidence.summary,artifacts:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,verificationResult:e.evidence.verificationResult??null,...(t.phase==="build"||t.phase==="verify")&&(t.phase==="build"?l.bundle.scope.scopeHash:m.envelope.implementationScopeHash)?{implementationScopeHash:t.phase==="build"?l.bundle.scope.scopeHash:m.envelope.implementationScopeHash}:{},...f?{repairScopeHash:f}:{},...d?{repairStagnation:d}:{}};t.phase==="build"&&l&&await vu({paths:e.paths,state:t,preparation:l}),t.phase==="verify"&&m&&await Tb({paths:e.paths,state:t,preparation:m});let R=await Wo({paths:e.paths,previousState:t,nextState:N,previousRun:a,nextRun:E,evidenceHash:r,eventData:S,now:e.now,transitionId:e.transitionId});await e.hooks?.afterPrepared?.(R);let w=await Ni(e.paths,e.name,e.hooks);if(!w)throw new Error("Native transition journal disappeared before completion");let y=h&&h.disposition!=="continue"?ei({paths:e.paths,state:w,findings:[wp(h)]}):[],g=h?.disposition==="manual-stop"||h?.disposition==="hard-stop";return{change:w,previousPhase:i,next:g?"manual":"auto",nextCommand:g?null:w.phase==="archive"?`comet native archive ${w.name} --dry-run`:null,findings:y,continuation:De({state:w,findings:y,archiveReady:w.phase==="archive"&&w.verification_result==="pass",clarificationMode:e.clarificationMode}),...u?{preparedScope:u}:{},...h?{repair:h}:{}}}async function Lk(e,t){let i=oe(e,"change name"),n=X(e,"--summary");if(!n)throw new j("--summary is required");let r=ut(e,"--confirmed"),a=Ki(e,"--artifact"),o=X(e,"--no-code-reason"),s=X(e,"--allow-partial-scope"),c=X(e,"--partial-reason"),l=X(e,"--result"),u=X(e,"--report"),d=X(e,"--override-repair"),f=X(e,"--override-summary");if(l!==void 0&&l!=="pass"&&l!=="fail")throw new j("--result must be pass or fail");if(s===void 0!=(c===void 0))throw new j("--allow-partial-scope and --partial-reason must be provided together");if(s&&!/^[a-f0-9]{64}$/u.test(s))throw new j("--allow-partial-scope must be a SHA-256 hash");if(s&&!r)throw new j("--allow-partial-scope requires --confirmed");if(d===void 0!=(f===void 0))throw new j("--override-repair and --override-summary must be provided together");if(d&&!/^[a-f0-9]{64}$/u.test(d))throw new j("--override-repair must be a SHA-256 hash");if(d&&l!==void 0)throw new j("--override-repair cannot be combined with --result");G(e);let{config:p,paths:m}=await _e(t),h={summary:n,...r?{confirmed:!0}:{},...a.length>0?{artifacts:a}:{},...o?{noCodeReason:o}:{},...s?{allowPartialScopeHash:s}:{},...c?{partialReason:c}:{},...l?{verificationResult:l}:{},...u?{verificationReport:u}:{},...d?{repairOverrideSignature:d}:{},...f?{repairOverrideSummary:f}:{}},v=await Fk({paths:m,name:i,evidence:h,clarificationMode:p.native.clarification_mode,maxVerifyFailures:p.native.max_verify_failures});if(v.next==="manual"){let E=v.repair?.disposition==="manual-stop"||v.repair?.disposition==="hard-stop"||v.findings.some(N=>["repair-stagnation-stop","repair-iteration-limit","repair-override-exhausted"].includes(N.code));return{command:"next",exitCode:E?75:65,data:v,error:{code:E?"blocked":"invalid-data",message:v.findings[0]?.message??"Native phase guard failed"}}}let b=await Ye(m,i,{clarificationMode:p.native.clarification_mode,maxVerifyFailures:p.native.max_verify_failures});return ee("next",{...v,continuation:b.continuation})}import vD from"node:path";var gD="Native receipt re-issued after revision bump";function wD(e){return!e.ok&&e.mismatches.length===1&&e.mismatches[0]?.startsWith("sourceRevision: ")===!0}function yD(e){return e.kind!=="automated-check"?"<unknown automated receipt>":[e.evidence.executable,...e.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function ND(e){return`${gD} to revision ${e}`}function bD(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function qk(e){let t=await W(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${t.phase} for ${e.name}`);if(!t.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};let i=await Zo(e.paths,t),n=await On(e.paths,e.name,t.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let R of l){let w=await oa(e.paths,e.name,R),y=Kl(w,i.bindings);if(!y.ok)if(c.add(R),w.kind==="manual-evidence"){let g={oldRef:R,acceptanceIds:[...w.acceptanceIds]};wD(y)?r.push(g):a.push({...g,mismatches:y.mismatches})}else w.kind==="automated-check"?o.push({oldRef:R,acceptanceIds:[...w.acceptanceIds],command:yD(w),timeoutMs:w.evidence.timeoutMs}):w.kind==="static-inspection"&&s.push({oldRef:R})}if(!(e.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:t.verification_report};let d=[],f=new Map,p=new Map;for(let R of r){let w=[...R.acceptanceIds].sort().join(`
239
+ `)}import{randomUUID as dD}from"crypto";import{promises as Q0}from"fs";import Rk from"path";function Z0(e){return{valid:e.length===0,findings:e}}async function eD(e,t){let i=[];if((t.noCodeReason??"").trim().length>0)return i;if(!t.artifacts||t.artifacts.length===0)return[{code:"build-evidence-missing",message:"Build requires an artifact reference or an explicit no-code reason"}];for(let n of t.artifacts){if(Rk.isAbsolute(n)||n.split(/[\\/]/u).includes("..")||/^(?:[A-Za-z]:|~|[\\/])/u.test(n)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}let r=Rk.resolve(e.projectRoot,...n.split(/[\\/]/u));if(!$(e.projectRoot,r)){i.push({code:"build-artifact-unsafe",message:`Unsafe build artifact: ${n}`});continue}try{await Q0.access(r)}catch{i.push({code:"build-artifact-missing",message:`Build artifact does not exist: ${n}`,path:n})}}return i}async function Ck(e){let t=[],i=C(e.paths,e.state.name);if(e.evidence.summary.trim().length===0&&t.push({code:"transition-summary-missing",message:"Phase transition requires a summary"}),e.evidence.confirmed&&e.state.phase!=="shape"&&e.state.phase!=="build"&&t.push({code:"confirmation-not-shape",message:"Explicit confirmation is only valid while leaving Shape or Build"}),t.push(...await nu(e.paths,e.state)),e.state.phase==="shape"||e.state.phase==="build"){let n=await hi(e.paths,e.state.name);if(n===null)t.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let r=await Nn(e.paths,n);r.complete||t.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${r.omittedCount} omitted entries); resolve the omissions before advancing`})}}if(e.state.phase==="shape"){let n=await ir(i,e.state.brief),r=await Xr(e.paths,e.state);t.push(...n.findings,...r.findings),t.length===0&&!e.evidence.confirmed&&t.push({code:"shape-confirmation-required",message:"Native clarification requires explicit user confirmation of the shared understanding before Build"})}else if(e.state.phase==="build")t.push(...(await ir(i,e.state.brief)).findings,...(await Xr(e.paths,e.state)).findings),t.push(...await eD(e.paths,e.evidence)),t.length===0&&e.state.approval!=="confirmed"&&!e.evidence.confirmed&&t.push({code:"approval-confirmation-required",message:"Native approval is implicit; confirm the current shared understanding before leaving Build"});else if(e.state.phase==="verify"){let n=e.evidence.verificationReport??e.state.verification_report;n?t.push(...(await Yr(i,n)).findings):t.push({code:"verification-report-missing",message:"Verify requires a report path"}),e.evidence.verificationResult||t.push({code:"verification-result-missing",message:"Verify requires pass or fail"}),t.push(...(await Xr(e.paths,e.state)).findings)}else t.push({code:"archive-command-required",message:"Use comet native archive for the Archive phase"});return Z0(t)}import{promises as vp}from"node:fs";import gp from"node:path";var Ak={maxDeclaredArtifacts:128,maxArtifactPathBytes:512};function Pk(e,t){if(e.omitted.some(i=>i.reason==="git-selection-changed"))throw new Error(`Native Git selection changed while capturing the ${t}; stabilize the Git index and retry Build evidence`);if(e.omitted.some(i=>i.reason==="physical-enumeration-limit"||i.reason==="physical-selection-changed"))throw new Error(`Native physical selection was incomplete or changed while capturing the ${t}; retry Build evidence with a stable bounded project tree`)}function tD(e,t){let i=t.omitted.slice(0,20).map(a=>a.path),n=t.omitted.reduce((a,o)=>(a[o.reason]=(a[o.reason]??0)+1,a),{}),r=t.omissionOverflow?.count??0;return r>0&&(n.overflow=r),new pi(e,t.omittedCount,n,i,t.omitted.length>i.length||r>0)}function iD(e,t,i){let n=new Set(i.entries.map(a=>a.path)),r=t.entries.filter(a=>!n.has(a.path)).slice(0,20).map(a=>a.path);return new pi(e,i.omittedCount,{"manifest-size":i.omittedCount},r,i.omittedCount>r.length)}function nD(e,t){let i=e.replaceAll("\\","/").trim();if(i.length===0||i!==e.replaceAll("\\","/")||gp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(i)||i.split("/").includes("..")||gp.posix.normalize(i)!==i||i==="."||i.endsWith("/")||Buffer.byteLength(i,"utf8")>Ak.maxArtifactPathBytes||Array.from(i).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127}))throw new Error(`${t} must be a normalized project-relative path`);return i}function rD(e,t){return e.entries.some(i=>i.path===t)?"file":e.entries.some(i=>i.path.startsWith(`${t}/`))?"directory":null}async function aD(e,t,i){let n=nD(i,"Native build artifact"),r=Za(e,n);if(r)throw new Error(`Native build artifact is excluded as ${r}: ${n}`);let a=gp.resolve(e.projectRoot,...n.split("/"));if(!$(e.projectRoot,a))throw new Error(`Native build artifact escapes the project: ${n}`);await A(e.projectRoot,a);try{let o=await vp.lstat(a);if(o.isSymbolicLink())throw new Error(`Native build artifact must not be a symlink or junction: ${n}`);let s=await vp.realpath(a),c=await vp.realpath(e.projectRoot);if(!$(c,s))throw new Error(`Native build artifact resolves outside the project: ${n}`);if(o.isFile())return{path:n,kind:"file"};if(o.isDirectory())return{path:n,kind:"directory"};throw new Error(`Native build artifact is not a file or directory: ${n}`)}catch(o){if(o.code!=="ENOENT")throw o;let s=rD(t,n);if(s===null)throw new Error(`Native build artifact does not exist: ${n}`,{cause:o});return{path:n,kind:s}}}async function oD(e){if(e.refs.length>Ak.maxDeclaredArtifacts)throw new Error("Native build evidence exceeds its declared-artifact budget");let t=await Promise.all(e.refs.map(i=>aD(e.paths,e.baseline,i)));if(t.sort((i,n)=>i.path.localeCompare(n.path)||i.kind.localeCompare(n.kind)),new Set(t.map(i=>i.path)).size!==t.length)throw new Error("Native build evidence contains duplicate or conflicting artifacts");return t}function sD(e){return e.map(t=>({code:"verification-scope-partial",message:`${t.id}: ${t.reason}`,...t.path===null?{}:{path:t.path}}))}function cD(e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error("Native partial allowance requires a scope hash");return e}async function xk(e){if(e.state.phase!=="build")throw new Error(`Native build evidence requires Build, got ${e.state.phase}`);if((e.noCodeReason??"").trim().length>0&&e.artifactRefs.length>0)throw new Error("Native build evidence cannot combine artifacts with a no-code reason");let t=await hi(e.paths,e.state.name);if(t===null)throw new Error("Native change has no baseline content snapshot");let i=await Nn(e.paths,t);if(Pk(i,"baseline projection"),!i.complete)throw tD(e.state.name,i);let n=await bt({changeDir:C(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await oD({paths:e.paths,baseline:i,refs:e.artifactRefs}),a=await bn(e.paths,i,{origin:"explicit",now:e.now});Pk(a,"current snapshot");let o=Tn({baseline:i,current:a,contractHash:n.contract.contractHash,declaredArtifacts:r,noCodeReason:e.noCodeReason??null});if(!o.baseline.complete)throw iD(e.state.name,i,o.baseline);let s=wt("scopes",o.scope.scopeHash);if(o.scope.complete){if(e.allowPartialScopeHash!==void 0&&e.allowPartialScopeHash!==null||e.partialReason!==void 0&&e.partialReason!==null)throw new Error("Complete Native build evidence must not include a partial allowance");return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:[],unresolvedScopes:[]}}if(e.allowPartialScopeHash===void 0||e.allowPartialScopeHash===null)return{contract:n,bundle:o,scopeRef:s,allowance:null,allowanceRef:null,findings:sD(o.scope.unresolvedScopes),unresolvedScopes:o.scope.unresolvedScopes};if(!e.confirmed)throw new Error("Native partial verification requires explicit confirmation");if(cD(e.allowPartialScopeHash)!==o.scope.scopeHash)throw new Error("Native partial allowance does not match the current implementation scope");let l=Fy({change:e.state.name,scopeBundle:o,allowedScopeIds:o.scope.unresolvedScopes.map(d=>d.id),reason:e.partialReason??"",confirmedSummary:e.confirmedSummary??"",sourceRevision:e.state.revision,now:e.now}),u=wt("allowances",l.allowanceHash);return{contract:n,bundle:o,scopeRef:s,allowance:l,allowanceRef:u,findings:[],unresolvedScopes:o.scope.unresolvedScopes}}async function vu(e){if(await dN({paths:e.paths,name:e.state.name,bundle:e.preparation.bundle})!==e.preparation.scopeRef)throw new Error("Native implementation scope persistence ref changed");if(e.includeAllowance===!1||e.preparation.allowance===null)return;if(await fN({paths:e.paths,name:e.state.name,allowance:e.preparation.allowance})!==e.preparation.allowanceRef)throw new Error("Native partial allowance persistence ref changed")}import{promises as Tk}from"fs";import _k from"path";var Ik=Yt.maxSpecs*4;async function gu(e){try{return await rt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function wu(e,t){let i=_k.join(C(e,t),"specs"),n;try{n=await ui({root:e.nativeRoot,directory:i,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let r=[],a=0,o=await Tk.opendir(i);try{for await(let s of o){if(a+=1,a>Ik)throw new Error(`Native proposed specs directory exceeds ${Ik} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Vt(s.name);let c=_k.join(i,s.name,"spec.md");await A(e.nativeRoot,c);let l;try{l=await Tk.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(r.push(s.name),r.length>Yt.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await n.verify(),r.sort()}async function jk(e,t){let i=new Map(t.spec_changes.map(a=>[a.capability,a])),n=await wu(e,t.name),r=[];for(let a of n){let o=i.get(a);if(o?.operation==="remove")throw new Error(`Capability ${a} has both a proposed spec and a remove intent`);if(o){r.push({...o,source:`specs/${a}/spec.md`});continue}let s=Jt(e,a);await A(e.nativeRoot,s);let c=await gu(s);r.push({capability:a,operation:c===null?"create":"replace",source:`specs/${a}/spec.md`,base_hash:c})}for(let a of t.spec_changes)a.operation==="remove"&&!n.includes(a.capability)&&r.push(a);return r.sort((a,o)=>a.capability.localeCompare(o.capability))}async function lD(e,t){let i=await wu(e,t.name),n=[];for(let r of i){if(t.spec_changes.find(c=>c.capability===r)?.operation==="remove")throw new Error(`Capability ${r} has both a proposed spec and a remove intent`);let o=Jt(e,r);await A(e.nativeRoot,o);let s=await gu(o);n.push({capability:r,operation:s===null?"create":"replace",source:`specs/${r}/spec.md`,base_hash:s})}for(let r of t.spec_changes){if(r.operation!=="remove"||i.includes(r.capability))continue;let a=Jt(e,r.capability);await A(e.nativeRoot,a);let o=await gu(a);o!==null&&n.push({...r,base_hash:o})}return n.sort((r,a)=>r.capability.localeCompare(a.capability))}async function Ok(e){Vt(e.name);let t=Ne(e.summary);return $n(t,"Spec rebase summary"),re(e.paths,`rebase specs for ${e.name}`,()=>He(e.paths,e.name,`rebase specs for ${e.name}`,async()=>{await St(e.paths,e.name);let i=await W(e.paths,e.name);if(i.phase==="shape")throw new Error("Shape spec metadata is refreshed by the next command");if(i.archived)throw new Error(`Native change ${i.name} is already archived`);let n=C(e.paths,e.name),r=await ye(n);if(!r||r.runId!==i.run_id||r.currentStep!==i.phase||r.pending)throw new Error(`Native Run state is missing or inconsistent for ${i.name}`);let a=await lD(e.paths,i),o={...i,revision:i.revision+1,phase:"build",spec_changes:a,verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},s={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},c=F(JSON.stringify({operation:"spec-rebase",change:i.name,summary:t,specChanges:a}));await Wo({paths:e.paths,previousState:i,nextState:o,previousRun:r,nextRun:s,evidenceHash:c,eventData:{previousPhase:i.phase,nextPhase:"build",evidenceHash:c,summary:t,artifacts:[],noCodeReason:null,verificationResult:null},operation:"spec-rebase",now:e.now,transitionId:e.transitionId});let l=await Ni(e.paths,e.name);if(!l)throw new Error("Native spec rebase journal disappeared before completion");return l}))}async function $k(e,t,i){return Vt(t),Vt(i),re(e,`remove spec ${i} from ${t}`,()=>He(e,t,`remove spec ${i} from ${t}`,async()=>(await St(e,t),uD(e,t,i))))}async function uD(e,t,i){let n=await W(e,t);if(n.phase==="archive"||n.archived)throw new Error(`Native change ${t} no longer accepts spec changes`);if((await wu(e,t)).includes(i))throw new Error(`Capability ${i} has both a proposed spec and a remove intent`);if(n.spec_changes.find(l=>l.capability===i)?.operation==="remove")return n;let o=Jt(e,i);await A(e.nativeRoot,o);let s=await gu(o);if(s===null)throw new Error(`Canonical spec is missing: ${i}`);let c={...n,spec_changes:[...n.spec_changes.filter(l=>l.capability!==i),{capability:i,operation:"remove",base_hash:s}].sort((l,u)=>l.capability.localeCompare(u.capability))};return await Gr(e,c,n.revision),c}async function Hk(e,t){let i=C(e,t),n={},r=0;for(let a of await wu(e,t)){let o=await ge({root:i,ref:`specs/${a}/spec.md`,maxBytes:Yt.maxFileBytes});if(r+=o.size,r>Yt.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");n[a]=o.text}return n}function fD(e){return`Native verification receipt binding is invalid: ${e.detail}. Re-issue the affected receipts with \`comet native receipt refresh ${e.change} --apply\`.`}function Mk(e){return e.confirmed!==void 0||e.artifacts!==void 0||e.noCodeReason!==void 0||e.allowPartialScopeHash!==void 0||e.partialReason!==void 0||e.verificationResult!==void 0||e.verificationReport!==void 0||e.repairOverrideSignature!==void 0||e.repairOverrideSummary!==void 0}function wp(e){return e.reasonCode==="override-already-used"?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${e.signatureHash}`}:e.disposition==="warn"?{code:"repair-stagnation-warning",message:`Native repair repeated the same failure signature: ${e.signatureHash}`}:e.disposition==="manual-stop"?{code:"repair-stagnation-stop",message:`Native repair stopped after repeated failure signature: ${e.signatureHash}`}:{code:"repair-iteration-limit",message:`Native repair reached its total iteration limit at signature: ${e.signatureHash}`}}function hD(e){if($n(e.summary,"Native transition summary"),e.noCodeReason!==void 0&&$n(e.noCodeReason,"Native transition no-code reason"),e.repairOverrideSignature!==void 0&&!/^[a-f0-9]{64}$/u.test(e.repairOverrideSignature))throw new Error("Native repair override signature must be a SHA-256 hash");e.repairOverrideSummary!==void 0&&jl(e.repairOverrideSummary)}function pD(e){return{...e,summary:Ne(e.summary),...e.noCodeReason===void 0?{}:{noCodeReason:Ne(e.noCodeReason)},...e.partialReason===void 0?{}:{partialReason:Ne(e.partialReason)},...e.repairOverrideSummary===void 0?{}:{repairOverrideSummary:Ne(e.repairOverrideSummary)}}}function mD(e,t){let i=t.repairOverrideSignature!==void 0,n=t.repairOverrideSummary!==void 0;if(i!==n)throw new Error("Native repair override signature and summary must be provided together");if((i||n)&&e.phase!=="build")throw new Error("Native repair override is only valid while leaving Build")}async function Dk(e){if(Mk(e.transition.evidence))throw new Error("Native evidence retreat only accepts a transition summary");let t=e.state.phase;if(t!=="verify"&&t!=="archive"||e.run.currentStep!==t||e.run.pending!==null)throw new Error("Native Verify/Archive Run cannot retreat evidence safely");if(t==="archive"?["complete","partial"].includes((await fr({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness):(await es({paths:e.transition.paths,state:e.state,now:e.transition.now})).freshness==="fresh"){let c=ei({paths:e.transition.paths,state:e.state,findings:[t==="archive"?{code:"archive-command-required",message:"Current verification evidence is fresh; use Native Archive preview"}:{code:"verification-result-missing",message:"Current implementation scope is fresh; complete Verify with a result and report"}]});return{change:e.state,previousPhase:t,next:"manual",nextCommand:t==="archive"?`comet native archive ${e.state.name} --dry-run`:null,findings:c,continuation:De({state:e.state,archiveReady:t==="archive",clarificationMode:e.transition.clarificationMode})}}let n={...e.state,revision:e.state.revision+1,phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null},r={...e.run,currentStep:"build",iteration:e.run.iteration+1,pending:null,status:"running"},a={previousPhase:t,nextPhase:"build",evidenceHash:e.evidenceHash,summary:e.transition.evidence.summary,artifacts:[],noCodeReason:null,verificationResult:null},o=await Wo({paths:e.transition.paths,previousState:e.state,nextState:n,previousRun:e.run,nextRun:r,evidenceHash:e.evidenceHash,eventData:a,operation:"evidence-retreat",now:e.transition.now,transitionId:e.transition.transitionId});await e.transition.hooks?.afterPrepared?.(o);let s=await Ni(e.transition.paths,e.state.name,e.transition.hooks);if(!s)throw new Error("Native evidence retreat journal disappeared before completion");return{change:s,previousPhase:t,next:"auto",nextCommand:null,findings:[],continuation:De({state:s,clarificationMode:e.transition.clarificationMode})}}async function Fk(e){let t={...e,maxVerifyFailures:e.maxVerifyFailures??Tg,evidence:pD(e.evidence)};return hD(t.evidence),re(e.paths,`advance ${e.name}`,()=>He(e.paths,e.name,`advance ${e.name}`,()=>vD(t)))}async function vD(e){await St(e.paths,e.name);let t=await W(e.paths,e.name),i=t.phase,n=C(e.paths,e.name),r=Hl(e.evidence),a=await ye(n);if(a){let x=(await qe(n,a.trajectoryRef)).at(-1);if(x?.type==="state_transitioned"&&x.data.evidenceHash===r&&x.data.nextPhase===t.phase&&(x.data.previousPhase==="verify"?["complete","partial"].includes((await fr({paths:e.paths,state:t,now:e.now})).freshness):!0)){let D=Object.hasOwn(x.data,"repairStagnation")?await AS(e.paths,t,e.maxVerifyFailures):null,z=D&&D.disposition!=="continue"?ei({paths:e.paths,state:t,findings:[wp(D)]}):[],ne=D?.disposition==="manual-stop"||D?.disposition==="hard-stop";return{change:t,previousPhase:x.data.previousPhase??t.phase,next:ne?"manual":"auto",nextCommand:ne?null:t.phase==="archive"?`comet native archive ${t.name} --dry-run`:null,findings:z,continuation:De({state:t,findings:z,archiveReady:t.phase==="archive"&&t.verification_result==="pass",clarificationMode:e.clarificationMode}),...D?{repair:D}:{}}}}if(t.phase==="archive"){if(!a)throw new Error("Native Archive Run state is missing");return Dk({transition:e,state:t,run:a,evidenceHash:r})}if(t.phase==="verify"&&!Mk(e.evidence)){if(!a)throw new Error("Native Verify Run state is missing");if((await es({paths:e.paths,state:t,now:e.now})).freshness!=="fresh")return Dk({transition:e,state:t,run:a,evidenceHash:r})}let o={...t,spec_changes:await jk(e.paths,t)};mD(t,e.evidence);let s=await Ck({paths:e.paths,state:o,evidence:e.evidence,clarificationMode:e.clarificationMode});if(!s.valid){let k=ei({paths:e.paths,state:t,findings:s.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode})}}let c=t.phase==="shape"?await bt({changeDir:n,briefRef:o.brief,specChanges:o.spec_changes}):null;if(t.phase!=="build"&&(e.evidence.allowPartialScopeHash!==void 0||e.evidence.partialReason!==void 0))throw new Error("Native partial scope allowance is only valid while leaving Build");let l=t.phase==="build"?await xk({paths:e.paths,state:o,artifactRefs:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,allowPartialScopeHash:e.evidence.allowPartialScopeHash??null,partialReason:e.evidence.partialReason??null,confirmedSummary:e.evidence.summary,confirmed:e.evidence.confirmed??!1,now:e.now}):null;if(l&&(t.approved_contract_hash??null)!==l.contract.contract.contractHash&&!e.evidence.confirmed){let k=ei({paths:e.paths,state:t,findings:[{code:"contract-changed-after-approval",message:"Native contract changed after approval; re-confirm the current contract before leaving Build"}]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode})}}let u=l?{scopeHash:l.bundle.scope.scopeHash,scopeRef:l.scopeRef,complete:l.bundle.scope.complete,unresolvedScopeCount:l.unresolvedScopes.length,partialAllowanceRef:l.allowanceRef,acceptancePage:Ll({criteria:l.contract.contract.acceptance,acceptanceHash:l.contract.contract.acceptanceHash})}:void 0;if(l&&l.findings.length>0){await vu({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let k=ei({paths:e.paths,state:t,findings:l.findings});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode}),preparedScope:u}}let d=null,f=l?la(l.bundle):null;if(t.phase==="build"&&l){let k=await _S({paths:e.paths,state:t,currentImplementationScope:l.bundle,maxVerifyFailures:e.maxVerifyFailures,...e.evidence.repairOverrideSignature&&e.evidence.repairOverrideSummary?{override:{expectedSignatureHash:e.evidence.repairOverrideSignature,summary:e.evidence.repairOverrideSummary}}:{}});if(k.disposition!=="proceed"){await vu({paths:e.paths,state:t,preparation:l,includeAllowance:!1});let x=ei({paths:e.paths,state:t,findings:[k.disposition==="hard-stop"&&k.overrideRecorded?{code:"repair-override-exhausted",message:`Native repair already used its override for signature: ${k.signatureHash}`}:wp({disposition:k.disposition,reasonCode:k.disposition==="hard-stop"?"repair-iteration-limit":"repeated-failure-stop",signatureHash:k.signatureHash})]});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:x,continuation:De({state:t,findings:x,clarificationMode:e.clarificationMode}),preparedScope:u&&{...u,partialAllowanceRef:null}}}d=k.eventProjection}let p=t.phase==="verify"&&e.evidence.verificationResult==="pass"?(await tp({paths:e.paths,name:t.name})).ref:null,m=t.phase==="verify"?await xb({paths:e.paths,state:o,result:e.evidence.verificationResult,reportRef:e.evidence.verificationReport,receiptRef:p,now:e.now}):null;if(m&&!m.ready){let k=ei({paths:e.paths,state:t,findings:m.findingCodes.map(x=>{if(x==="verification-receipt-binding-mismatch"&&m.receiptBindingFailures&&m.receiptBindingFailures.length>0){let U=m.receiptBindingFailures.map(D=>`${D.acceptanceId?`${D.ref}[${D.acceptanceId}]`:D.ref} -> ${D.mismatches.join("; ")}`).join(" | ");return{code:x,message:fD({change:t.name,detail:U})}}return{code:x,message:`Native verification evidence is not current: ${x}`}})});return{change:t,previousPhase:i,next:"manual",nextCommand:null,findings:k,continuation:De({state:t,findings:k,clarificationMode:e.clarificationMode})}}let h=null;if(t.phase==="verify"&&e.evidence.verificationResult==="fail"&&m?.ready&&m.envelope){let k=await TS({paths:e.paths,state:t,envelope:m.envelope,maxVerifyFailures:e.maxVerifyFailures});d=k.eventProjection,f=k.facts.implementationScopeHash,h=xS(k)}let v=a;if(!v){if(t.run_id!==null||t.phase!=="shape")throw new Error("Native Run state is missing or inconsistent");v=Iw(ct,e.runId?.()??dD(),cr)}if(v.currentStep!==t.phase)throw new Error(`Native Run step ${v.currentStep??"(none)"} does not match ${t.phase}`);let b=ms(ct,v,new Set,ua,void 0);if(!b.action)throw new Error(b.reason??"Native runtime produced no action");let E=vs(ct,b.state,{actionId:b.action.id,status:"succeeded",summary:e.evidence.summary,state:e.evidence.verificationResult?{verification_result:e.evidence.verificationResult}:void 0},ua,void 0);if(!E.currentStep)throw new Error("Archive completion must use the archive command");let N={...o,revision:t.revision+1,phase:E.currentStep,approval:e.evidence.confirmed?"confirmed":t.approval,approved_contract_hash:t.phase==="shape"?c.contract.contractHash:t.phase==="build"&&e.evidence.confirmed?l.contract.contract.contractHash:t.approved_contract_hash??null,run_id:v.runId,...t.phase==="build"?{verification_result:"pending",verification_report:null,implementation_scope:l.scopeRef,partial_allowance:l.allowanceRef,verification_evidence:null}:{},...t.phase==="verify"?{verification_result:e.evidence.verificationResult,verification_report:m.envelope.reportRef,verification_evidence:m.evidenceRef}:{}},S={previousPhase:i,nextPhase:N.phase,evidenceHash:r,summary:e.evidence.summary,artifacts:e.evidence.artifacts??[],noCodeReason:e.evidence.noCodeReason??null,verificationResult:e.evidence.verificationResult??null,...(t.phase==="build"||t.phase==="verify")&&(t.phase==="build"?l.bundle.scope.scopeHash:m.envelope.implementationScopeHash)?{implementationScopeHash:t.phase==="build"?l.bundle.scope.scopeHash:m.envelope.implementationScopeHash}:{},...f?{repairScopeHash:f}:{},...d?{repairStagnation:d}:{}};t.phase==="build"&&l&&await vu({paths:e.paths,state:t,preparation:l}),t.phase==="verify"&&m&&await Tb({paths:e.paths,state:t,preparation:m});let R=await Wo({paths:e.paths,previousState:t,nextState:N,previousRun:a,nextRun:E,evidenceHash:r,eventData:S,now:e.now,transitionId:e.transitionId});await e.hooks?.afterPrepared?.(R);let w=await Ni(e.paths,e.name,e.hooks);if(!w)throw new Error("Native transition journal disappeared before completion");let y=h&&h.disposition!=="continue"?ei({paths:e.paths,state:w,findings:[wp(h)]}):[],g=h?.disposition==="manual-stop"||h?.disposition==="hard-stop";return{change:w,previousPhase:i,next:g?"manual":"auto",nextCommand:g?null:w.phase==="archive"?`comet native archive ${w.name} --dry-run`:null,findings:y,continuation:De({state:w,findings:y,archiveReady:w.phase==="archive"&&w.verification_result==="pass",clarificationMode:e.clarificationMode}),...u?{preparedScope:u}:{},...h?{repair:h}:{}}}async function Lk(e,t){let i=oe(e,"change name"),n=X(e,"--summary");if(!n)throw new j("--summary is required");let r=ut(e,"--confirmed"),a=Ki(e,"--artifact"),o=X(e,"--no-code-reason"),s=X(e,"--allow-partial-scope"),c=X(e,"--partial-reason"),l=X(e,"--result"),u=X(e,"--report"),d=X(e,"--override-repair"),f=X(e,"--override-summary");if(l!==void 0&&l!=="pass"&&l!=="fail")throw new j("--result must be pass or fail");if(s===void 0!=(c===void 0))throw new j("--allow-partial-scope and --partial-reason must be provided together");if(s&&!/^[a-f0-9]{64}$/u.test(s))throw new j("--allow-partial-scope must be a SHA-256 hash");if(s&&!r)throw new j("--allow-partial-scope requires --confirmed");if(d===void 0!=(f===void 0))throw new j("--override-repair and --override-summary must be provided together");if(d&&!/^[a-f0-9]{64}$/u.test(d))throw new j("--override-repair must be a SHA-256 hash");if(d&&l!==void 0)throw new j("--override-repair cannot be combined with --result");G(e);let{config:p,paths:m}=await _e(t),h={summary:n,...r?{confirmed:!0}:{},...a.length>0?{artifacts:a}:{},...o?{noCodeReason:o}:{},...s?{allowPartialScopeHash:s}:{},...c?{partialReason:c}:{},...l?{verificationResult:l}:{},...u?{verificationReport:u}:{},...d?{repairOverrideSignature:d}:{},...f?{repairOverrideSummary:f}:{}},v=await Fk({paths:m,name:i,evidence:h,clarificationMode:p.native.clarification_mode,maxVerifyFailures:p.native.max_verify_failures});if(v.next==="manual"){let E=v.repair?.disposition==="manual-stop"||v.repair?.disposition==="hard-stop"||v.findings.some(N=>["repair-stagnation-stop","repair-iteration-limit","repair-override-exhausted"].includes(N.code));return{command:"next",exitCode:E?75:65,data:v,error:{code:E?"blocked":"invalid-data",message:v.findings[0]?.message??"Native phase guard failed"}}}let b=await Ye(m,i,{clarificationMode:p.native.clarification_mode,maxVerifyFailures:p.native.max_verify_failures});return ee("next",{...v,continuation:b.continuation})}import gD from"node:path";var wD="Native receipt re-issued after revision bump";function yD(e){return!e.ok&&e.mismatches.length===1&&e.mismatches[0]?.startsWith("sourceRevision: ")===!0}function ND(e){return e.kind!=="automated-check"?"<unknown automated receipt>":[e.evidence.executable,...e.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function bD(e){return`${wD} to revision ${e}`}function SD(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function qk(e){let t=await W(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${t.phase} for ${e.name}`);if(!t.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};let i=await Zo(e.paths,t),n=await On(e.paths,e.name,t.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let R of l){let w=await oa(e.paths,e.name,R),y=Kl(w,i.bindings);if(!y.ok)if(c.add(R),w.kind==="manual-evidence"){let g={oldRef:R,acceptanceIds:[...w.acceptanceIds]};yD(y)?r.push(g):a.push({...g,mismatches:y.mismatches})}else w.kind==="automated-check"?o.push({oldRef:R,acceptanceIds:[...w.acceptanceIds],command:ND(w),timeoutMs:w.evidence.timeoutMs}):w.kind==="static-inspection"&&s.push({oldRef:R})}if(!(e.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:t.verification_report};let d=[],f=new Map,p=new Map;for(let R of r){let w=[...R.acceptanceIds].sort().join(`
240
240
  `),y=p.get(w);y?y.push(R.oldRef):p.set(w,[R.oldRef])}for(let[R,w]of p){let y=R.split(`
241
- `),g=await Gl({paths:e.paths,name:e.name,acceptanceIds:y,steps:[ND(t.revision)],observations:[bD()]});for(let k of y)f.set(k,g.ref);for(let k of w){let x=r.find(U=>U.oldRef===k)?.acceptanceIds[0];x&&d.push({acceptanceId:x,oldRef:k,newRef:g.ref})}}let m=t.verification_report;if(!m)throw new Error(`Native receipt refresh cannot rewrite verification report: ${e.name} has no report ref`);let h=C(e.paths,e.name),v=await ge({root:h,ref:m}),b=ql(v.text),E=SD(n.acceptanceTrace.entries,b,c,f),N=Bl(E),S=kD(v.text,N);return await je(vD.join(h,...m.split("/")),S),{refreshed:d,requiresRerun:[],requiresManual:[],requiresCheck:s,applied:!0,verificationReport:m}}function SD(e,t,i,n){let r=new Map;for(let o of t)r.set(o.acceptance_id,o);let a=[];for(let o of e){let s=r.get(o.acceptanceId);if(!s)continue;if(o.status==="failed"){a.push(s);continue}let c=s.evidence_refs.filter(f=>!i.has(f)),l=n.get(o.acceptanceId),u=l!==void 0?[...c,l]:c;if(u.length===0){a.push(s);continue}let d={acceptance_id:s.acceptance_id,status:s.status,evidence_refs:[...new Set(u)].sort()};s.skipped_reason!==void 0&&(d.skipped_reason=s.skipped_reason),a.push(d)}return a}function kD(e,t){let i=e.indexOf(Uo);if(i<0)throw new Error("Native verification report is missing the acceptance-evidence start marker");let n=e.indexOf(da,i);if(n<0)throw new Error("Native verification report is missing the acceptance-evidence end marker");let r=e.slice(0,i),a=e.slice(n+da.length);return`${r}${t}${a}`}async function Bk(e,t){let i=oe(e,"receipt subcommand"),n=oe(e,"change name"),{paths:r}=await _e(t);if(i==="manual"){let a=Ki(e,"--acceptance"),o=Ki(e,"--step"),s=Ki(e,"--observation");G(e);let c=await Gl({paths:r,name:n,acceptanceIds:a,steps:o,observations:s});return ee("receipt manual",c,`Native manual receipt: ${c.ref}
241
+ `),g=await Gl({paths:e.paths,name:e.name,acceptanceIds:y,steps:[bD(t.revision)],observations:[SD()]});for(let k of y)f.set(k,g.ref);for(let k of w){let x=r.find(U=>U.oldRef===k)?.acceptanceIds[0];x&&d.push({acceptanceId:x,oldRef:k,newRef:g.ref})}}let m=t.verification_report;if(!m)throw new Error(`Native receipt refresh cannot rewrite verification report: ${e.name} has no report ref`);let h=C(e.paths,e.name),v=await ge({root:h,ref:m}),b=ql(v.text),E=kD(n.acceptanceTrace.entries,b,c,f),N=Bl(E),S=ED(v.text,N);return await je(gD.join(h,...m.split("/")),S),{refreshed:d,requiresRerun:[],requiresManual:[],requiresCheck:s,applied:!0,verificationReport:m}}function kD(e,t,i,n){let r=new Map;for(let o of t)r.set(o.acceptance_id,o);let a=[];for(let o of e){let s=r.get(o.acceptanceId);if(!s)continue;if(o.status==="failed"){a.push(s);continue}let c=s.evidence_refs.filter(f=>!i.has(f)),l=n.get(o.acceptanceId),u=l!==void 0?[...c,l]:c;if(u.length===0){a.push(s);continue}let d={acceptance_id:s.acceptance_id,status:s.status,evidence_refs:[...new Set(u)].sort()};s.skipped_reason!==void 0&&(d.skipped_reason=s.skipped_reason),a.push(d)}return a}function ED(e,t){let i=e.indexOf(Uo);if(i<0)throw new Error("Native verification report is missing the acceptance-evidence start marker");let n=e.indexOf(da,i);if(n<0)throw new Error("Native verification report is missing the acceptance-evidence end marker");let r=e.slice(0,i),a=e.slice(n+da.length);return`${r}${t}${a}`}async function Bk(e,t){let i=oe(e,"receipt subcommand"),n=oe(e,"change name"),{paths:r}=await _e(t);if(i==="manual"){let a=Ki(e,"--acceptance"),o=Ki(e,"--step"),s=Ki(e,"--observation");G(e);let c=await Gl({paths:r,name:n,acceptanceIds:a,steps:o,observations:s});return ee("receipt manual",c,`Native manual receipt: ${c.ref}
242
242
  `)}if(i==="automated"){let a=e.indexOf("--");if(a<0||a===e.length-1)throw new j("receipt automated requires -- <executable> [args...]");let o=e.splice(a+1);e.splice(a,1);let s=Ki(e,"--acceptance"),c=X(e,"--timeout-ms");G(e);let l=c===void 0?void 0:/^[1-9]\d*$/u.test(c)&&Number.isSafeInteger(Number(c))&&Number(c)<=Qo?Number(c):null;if(l===null)throw new j(`--timeout-ms must be an integer from 1 through ${Qo}`);let u=await kb({paths:r,name:n,acceptanceIds:s,command:o[0],args:o.slice(1),...l===void 0?{}:{timeoutMs:l}});return{command:"receipt automated",exitCode:u.receipt.status==="passed"?0:1,data:u,text:`Native automated receipt ${u.receipt.status}: ${u.ref}
243
243
  `}}if(i==="refresh"){let a=ut(e,"--apply"),o=ut(e,"--dry-run");if(G(e),a&&o)throw new j("receipt refresh --apply and --dry-run cannot be combined");let s=await qk({paths:r,name:n,apply:a}),c=[];if(s.refreshed.length>0){c.push(`Re-issued ${s.refreshed.length} manual receipt(s) at the current revision:`);for(let l of s.refreshed)c.push(` ${l.acceptanceId}: ${l.oldRef} -> ${l.newRef}`)}if(s.requiresRerun.length>0){c.push(`Re-run ${s.requiresRerun.length} stale automated receipt(s) (they cannot be re-issued without a real execution):`);for(let l of s.requiresRerun){let u=l.acceptanceIds.join(", ");c.push(` [${u}] ${l.command}`)}}if(s.requiresManual.length>0){c.push(`Re-run manual verification for ${s.requiresManual.length} receipt(s); contract, scope, snapshot, or artifact bindings changed:`);for(let l of s.requiresManual)c.push(` [${l.acceptanceIds.join(", ")}] ${l.mismatches.join("; ")}`)}return s.requiresCheck.length>0&&c.push(`Re-run \`comet native check ${n}\` to refresh ${s.requiresCheck.length} required-check receipt(s).`),s.applied?c.push(`Updated acceptance evidence in ${s.verificationReport}.`):s.refreshed.length===0&&s.requiresRerun.length===0&&s.requiresManual.length===0&&s.requiresCheck.length===0?c.push("No stale receipts found."):a?s.requiresManual.length>0&&c.push("Fresh manual verification is required before these receipts can be refreshed."):c.push("Dry run only. Re-run with --apply to re-issue manual receipts."),ee("receipt refresh",s,`${c.join(`
244
244
  `)}
@@ -246,6 +246,6 @@ Commands:
246
246
  `)}throw new j(`Unknown root command: ${i}`)}async function Jk(e,t){let i=oe(e,"change name");G(e);let{config:n,paths:r}=await _e(t);await eu(r,i);let a=await Ye(r,i,{clarificationMode:n.native.clarification_mode,maxVerifyFailures:n.native.max_verify_failures});return ee("select",{selected:i,continuation:a.continuation},`Selected Native change ${i}
247
247
  `)}async function zk(e,t){let i=oe(e,"change name");G(e);let{paths:n}=await _e(t),r=await ot(n,i);if(r.status==="migration-required")return ee("show",{name:i,schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,migrationRequired:!0,message:r.message});if(r.status!=="current"||!r.state)throw new Oi(r.schema,r.minimumRuntimeVersion);let a=r.state,o=C(n,i),s=await Hk(n,i),c=await ge({root:o,ref:a.brief,maxBytes:Yt.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>aS)throw new Error("Native show output exceeds its serialized byte budget");return ee("show",l)}async function Wk(e,t){let i=oe(e,"spec subcommand");if(i==="remove"){let n=oe(e,"change name"),r=oe(e,"capability");G(e);let{config:a,paths:o}=await _e(t),s=await $k(o,n,r),c=await Ye(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return ee("spec remove",{...s,continuation:c.continuation},`Marked Native capability ${r} for removal in ${n}
248
248
  `)}if(i==="rebase"){let n=oe(e,"change name"),r=X(e,"--summary");if(!r)throw new j("--summary is required");G(e);let{config:a,paths:o}=await _e(t),s=await Ok({paths:o,name:n,summary:r}),c=await Ye(o,s.name,{clarificationMode:a.native.clarification_mode,maxVerifyFailures:a.native.max_verify_failures});return ee("spec rebase",{...s,continuation:c.continuation},`Rebased Native specs for ${n}
249
- `)}throw new j(`Unknown spec command: ${i}`)}async function Uk(e,t){let i=ut(e,"--details"),n=X(e,"--cursor"),r=X(e,"--acceptance-cursor"),a=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!a)throw new j("status --details requires a change name");if(n&&a)throw new j("--cursor is only valid for status lists");if(n&&i)throw new j("--cursor cannot be combined with --details");if(r&&!i)throw new j("--acceptance-cursor requires status --details");if(r&&!a)throw new j("--acceptance-cursor requires a change name");G(e);let{config:o,paths:s}=await _e(t),c=a?await Ye(s,a,{details:i,...r?{acceptanceCursor:r}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures}):await rp(s,{...n?{cursor:n}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures});return ee("status",c)}var ED={"hook-guard":Sk,init:kk,root:Vk,new:Ek,spec:Wk,show:zk,status:Uk,select:Jk,checkpoint:DS,check:yS,evidence:fk,receipt:Bk,next:Lk,archive:fS,doctor:dk};async function RD(e,t){if(e.length===0||e[0]==="--help"||e[0]==="help")return{command:e[0]??null,exitCode:0,data:{usage:Qh},text:Qh};let i=e.shift(),n=await sS(t),r=ED[i];if(!r)throw new j(`Unknown Native command: ${i}`);return r(e,n)}async function Kk(e){let t=[...e],i=t.indexOf("--"),n=i<0?t:t.slice(0,i),r=i<0?[]:t.slice(i),a=n.includes("--json"),o,s=n[0]??null;try{ut(n,"--json"),o=X(n,"--project-root");let c=[...n,...r];return s=c[0]??null,Zh(await RD(c,o),a)}catch(c){return Zh(dS(s,c),a)}}async function PD(e=process.argv.slice(2)){let t=await Kk(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
249
+ `)}throw new j(`Unknown spec command: ${i}`)}async function Uk(e,t){let i=ut(e,"--details"),n=X(e,"--cursor"),r=X(e,"--acceptance-cursor"),a=e[0]?.startsWith("--")?void 0:e.shift();if(i&&!a)throw new j("status --details requires a change name");if(n&&a)throw new j("--cursor is only valid for status lists");if(n&&i)throw new j("--cursor cannot be combined with --details");if(r&&!i)throw new j("--acceptance-cursor requires status --details");if(r&&!a)throw new j("--acceptance-cursor requires a change name");G(e);let{config:o,paths:s}=await _e(t),c=a?await Ye(s,a,{details:i,...r?{acceptanceCursor:r}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures}):await rp(s,{...n?{cursor:n}:{},clarificationMode:o.native.clarification_mode,maxVerifyFailures:o.native.max_verify_failures});return ee("status",c)}var RD={"hook-guard":Sk,init:kk,root:Vk,new:Ek,spec:Wk,show:zk,status:Uk,select:Jk,checkpoint:DS,check:yS,evidence:fk,receipt:Bk,next:Lk,archive:fS,doctor:dk};async function CD(e,t){if(e.length===0||e[0]==="--help"||e[0]==="help")return{command:e[0]??null,exitCode:0,data:{usage:Qh},text:Qh};let i=e.shift(),n=await sS(t),r=RD[i];if(!r)throw new j(`Unknown Native command: ${i}`);return r(e,n)}async function Kk(e){let t=[...e],i=t.indexOf("--"),n=i<0?t:t.slice(0,i),r=i<0?[]:t.slice(i),a=n.includes("--json"),o,s=n[0]??null;try{ut(n,"--json"),o=X(n,"--project-root");let c=[...n,...r];return s=c[0]??null,Zh(await CD(c,o),a)}catch(c){return Zh(dS(s,c),a)}}async function AD(e=process.argv.slice(2)){let t=await Kk(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
250
250
  `)?"":`
251
- `)),t.exitCode}var Gk=process.argv[1];Gk&&import.meta.url===CD(Gk).href&&PD().then(e=>{process.exitCode=e});export{PD as main};
251
+ `)),t.exitCode}var Gk=process.argv[1];Gk&&import.meta.url===PD(Gk).href&&AD().then(e=>{process.exitCode=e});export{AD as main};