@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.
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +66 -66
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
- package/assets/skills/comet/scripts/comet-guard.mjs +88 -88
- package/assets/skills/comet/scripts/comet-handoff.mjs +68 -68
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +62 -62
- package/assets/skills/comet/scripts/comet-hook-router.mjs +64 -64
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +55 -55
- package/assets/skills/comet/scripts/comet-runtime.mjs +134 -134
- package/assets/skills/comet/scripts/comet-state.mjs +67 -67
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +6 -6
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +39 -39
- package/assets/skills/comet-native/scripts/comet-native-check.mjs +45 -45
- package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +35 -35
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +33 -33
- package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +7 -7
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +7 -7
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +6 -6
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +44 -44
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +27 -27
- package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +24 -24
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +43 -43
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +41 -41
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +7 -7
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +51 -51
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
- package/dist/app/commands/i18n.d.ts +1 -1
- package/dist/app/commands/i18n.d.ts.map +1 -1
- package/dist/app/commands/i18n.js +90 -0
- package/dist/app/commands/i18n.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +2 -0
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/project-scope-selection.d.ts +2 -1
- package/dist/app/commands/project-scope-selection.d.ts.map +1 -1
- package/dist/app/commands/project-scope-selection.js +5 -7
- package/dist/app/commands/project-scope-selection.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts +6 -0
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +197 -110
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +39 -1
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js +8 -4
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout.js +1 -0
- package/dist/domains/comet-classic/classic-layout.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js +2 -3
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +5 -2
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +32 -0
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts +6 -2
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +142 -18
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts +3 -0
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.js +15 -2
- package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
- package/dist/domains/workflow-contract/index.d.ts +1 -1
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -1
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config-reader.d.ts +2 -0
- package/dist/domains/workflow-contract/project-config-reader.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config-reader.js.map +1 -1
- package/dist/domains/workflow-contract/project-config-writer.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config-writer.js +3 -2
- package/dist/domains/workflow-contract/project-config-writer.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +1 -0
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +9 -4
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/platform/install/platforms.d.ts +2 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +1 -0
- package/dist/platform/install/platforms.js.map +1 -1
- 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)){Xo(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(mi(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(Tm(i.key)&&!mi(i.sep,"newline")){let o=jn(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(mi(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=jn(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]}):mi(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&&!mi(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)){Xo(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||mi(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=Yo(n),a=jn(r);xm(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=Yo(t),n=jn(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=Yo(t),n=jn(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())}}};_m.Parser=ku});var Hm=P(Xr=>{"use strict";var Im=uu(),KE=Br(),Yr=zr(),GE=cl(),YE=V(),XE=Su(),jm=Eu();function Om(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new XE.LineCounter||null,prettyErrors:t}}function QE(e,t={}){let{lineCounter:i,prettyErrors:n}=Om(t),r=new jm.Parser(i?.addNewLine),a=new Im.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(Yr.prettifyError(e,i)),s.warnings.forEach(Yr.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function $m(e,t={}){let{lineCounter:i,prettyErrors:n}=Om(t),r=new jm.Parser(i?.addNewLine),a=new Im.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 Yr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Yr.prettifyError(e,i)),o.warnings.forEach(Yr.prettifyError(e,i))),o}function ZE(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=$m(e,i);if(!r)return null;if(r.warnings.forEach(a=>GE.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 eR(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 YE.isDocument(e)&&!n?e.toString(i):new KE.Document(e,n,i).toString(i)}Xr.parse=ZE;Xr.parseAllDocuments=QE;Xr.parseDocument=$m;Xr.stringify=eR});var Zo=P(K=>{"use strict";var tR=uu(),iR=Br(),nR=Jl(),Ru=zr(),rR=Pr(),vi=V(),aR=di(),oR=le(),sR=hi(),cR=pi(),lR=Ko(),uR=Nu(),dR=Su(),fR=Eu(),Qo=Hm(),Dm=Sr();K.Composer=tR.Composer;K.Document=iR.Document;K.Schema=nR.Schema;K.YAMLError=Ru.YAMLError;K.YAMLParseError=Ru.YAMLParseError;K.YAMLWarning=Ru.YAMLWarning;K.Alias=rR.Alias;K.isAlias=vi.isAlias;K.isCollection=vi.isCollection;K.isDocument=vi.isDocument;K.isMap=vi.isMap;K.isNode=vi.isNode;K.isPair=vi.isPair;K.isScalar=vi.isScalar;K.isSeq=vi.isSeq;K.Pair=aR.Pair;K.Scalar=oR.Scalar;K.YAMLMap=sR.YAMLMap;K.YAMLSeq=cR.YAMLSeq;K.CST=lR;K.Lexer=uR.Lexer;K.LineCounter=dR.LineCounter;K.Parser=fR.Parser;K.parse=Qo.parse;K.parseAllDocuments=Qo.parseAllDocuments;K.parseDocument=Qo.parseDocument;K.stringify=Qo.stringify;K.visit=Dm.visit;K.visitAsync=Dm.visitAsync});import{promises as Aj}from"fs";import we from"path";import vr from"path";import{isDeepStrictEqual as lI}from"util";import{createHash as DN}from"crypto";function zf(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 Wf(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Wf(e[t]);return Object.freeze(e)}function oi(e){return Wf(structuredClone(e))}function Jc(e,t,i,n){return e.resolveStep({pkg:oi(t),state:oi(i),context:oi(n)})}function Uf(e,t,i,n,r,a){return e.resolveNext({pkg:oi(t),state:oi(i),step:oi(n),outcome:oi(r),context:oi(a)})}function MN(e,t,i){return DN("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function zc(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Kf(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=Jc(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=zc(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:MN(s.runId,s.iteration,o.id),stepId:o.id};return FN(e,s,c,i)}function FN(e,t,i,n){let r=zf(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 Gf(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"?Jc(n,e,t,r):void 0,o=a?zc(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"?Uf(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!zc(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 bd}from"fs";import Eg from"path";var Ys=Vc(Zo(),1);import{promises as mg}from"fs";import Wt from"path";import{createHash as vR}from"node:crypto";import{promises as mt}from"node:fs";import Ze from"node:path";import{TextDecoder as gR}from"node:util";import Pu from"path";var hR=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),pR=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function mR(e){return e.toLowerCase().startsWith(".env")}function Tt(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>mR(n))?"environment-file":i.some(n=>pR.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>hR.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Cu(e,t){let i=Tt(t);if(i)return i;let n=Pu.resolve(e.projectRoot,...t.split("/")),r=Pu.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Pu.resolve(e.configFile)?"native-runtime":null}function gi(e){return e!==0&&e!==0n&&e!=="0"}function Ee(e,t){return gi(e.dev)&&gi(t.dev)&&gi(e.ino)&&gi(t.ino)}function L(e,t){let i=gi(e.dev)&&gi(t.dev);if(i&&e.dev!==t.dev)return!1;let n=gi(e.ino)&&gi(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var Qr=1024*1024;function Au(e,t){let i=Ze.relative(e,t);return i===""||!Ze.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ze.sep}`)}function wR(e){let t=Ze.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})||Ze.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=Tt(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 yR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function NR(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function es(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Mm(e){let t=await mt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await mt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function bR(e,t){let i=Ze.resolve(e),n=Ze.resolve(t);if(!Au(i,n))throw new Error("Native artifact path is outside its root");let r=[await Mm(i)],a=i;for(let o of Ze.relative(i,n).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await Mm(a);if(!Au(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Fm(e){for(let t of e){let i=await mt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!NR(t,i)||await mt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function _e(e){let t=wR(e.ref),i=yR(e.maxBytes??Qr),n=Ze.resolve(e.root,...t.split("/")),r=await bR(e.root,Ze.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await mt.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 mt.realpath(n);if(!Au(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await mt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),mt.lstat(n),mt.realpath(n)]);if(await Fm(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!es(a,c)||!es(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 S=i+1-f,k=await s.read(p,0,Math.min(p.length,S),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),mt.lstat(n),mt.realpath(n)]);if(await Fm(r),!h.isFile()||h.isSymbolicLink()||v!==o||!es(c,m)||!es(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),b;try{b=new gR("utf-8",{fatal:!0}).decode(N)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:vR("sha256").update(N).digest("hex"),text:b}}finally{await s.close()}}import{randomUUID as SR}from"crypto";import{promises as Re}from"fs";import vt from"path";function Tu(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function kR(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xu(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Lm(e){let t=await Re.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 Re.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Zr(e){for(let t of e){let i=await Re.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!kR(t,i)||await Re.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ER(e,t){let i=vt.resolve(e),n=vt.resolve(t);if(!Tu(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Lm(i)],a=vt.relative(i,n).split(vt.sep).filter(Boolean),o=i;for(let s of a){await Zr(r),o=vt.join(o,s);try{await Re.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Lm(o);if(!Tu(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Zr(r),r}async function RR(e){let t;try{t=await Re.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 qm(e,t,i={}){let n=vt.dirname(e),r=i.containedRoot?await ER(i.containedRoot,n):null;r||await Re.mkdir(n,{recursive:!0});let a=vt.join(n,`.${vt.basename(e)}.${SR()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Re.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([Re.lstat(a),Re.realpath(a)]);if(await Zr(r),!c.isFile()||c.isSymbolicLink()||!xu(s,c)||!Tu(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(),!xu(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 Zr(r);let c=await Re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!xu(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Re.link(a,e),await Re.unlink(a)):await Re.rename(a,e),await RR(n)}catch(c){if(await o?.close(),!r)await Re.rm(a,{force:!0});else try{await Zr(r),await Re.rm(a,{force:!0})}catch{}throw c}}async function Le(e,t,i={}){await qm(e,t,i)}async function Bm(e,t,i={}){await qm(e,t,i)}async function pe(e,t,i={}){await Le(e,JSON.stringify(t,null,2)+`
|
|
143
|
-
`,i)}import
|
|
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=Yo(t),n=jn(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=Yo(t),n=jn(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())}}};_m.Parser=ku});var Hm=P(Xr=>{"use strict";var Im=uu(),KE=Br(),Yr=zr(),GE=cl(),YE=V(),XE=Su(),jm=Eu();function Om(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new XE.LineCounter||null,prettyErrors:t}}function QE(e,t={}){let{lineCounter:i,prettyErrors:n}=Om(t),r=new jm.Parser(i?.addNewLine),a=new Im.Composer(t),o=Array.from(a.compose(r.parse(e)));if(n&&i)for(let s of o)s.errors.forEach(Yr.prettifyError(e,i)),s.warnings.forEach(Yr.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function $m(e,t={}){let{lineCounter:i,prettyErrors:n}=Om(t),r=new jm.Parser(i?.addNewLine),a=new Im.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 Yr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Yr.prettifyError(e,i)),o.warnings.forEach(Yr.prettifyError(e,i))),o}function ZE(e,t,i){let n;typeof t=="function"?n=t:i===void 0&&t&&typeof t=="object"&&(i=t);let r=$m(e,i);if(!r)return null;if(r.warnings.forEach(a=>GE.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 eR(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 YE.isDocument(e)&&!n?e.toString(i):new KE.Document(e,n,i).toString(i)}Xr.parse=ZE;Xr.parseAllDocuments=QE;Xr.parseDocument=$m;Xr.stringify=eR});var Zo=P(K=>{"use strict";var tR=uu(),iR=Br(),nR=Jl(),Ru=zr(),rR=Pr(),vi=V(),aR=di(),oR=le(),sR=hi(),cR=pi(),lR=Ko(),uR=Nu(),dR=Su(),fR=Eu(),Qo=Hm(),Dm=Sr();K.Composer=tR.Composer;K.Document=iR.Document;K.Schema=nR.Schema;K.YAMLError=Ru.YAMLError;K.YAMLParseError=Ru.YAMLParseError;K.YAMLWarning=Ru.YAMLWarning;K.Alias=rR.Alias;K.isAlias=vi.isAlias;K.isCollection=vi.isCollection;K.isDocument=vi.isDocument;K.isMap=vi.isMap;K.isNode=vi.isNode;K.isPair=vi.isPair;K.isScalar=vi.isScalar;K.isSeq=vi.isSeq;K.Pair=aR.Pair;K.Scalar=oR.Scalar;K.YAMLMap=sR.YAMLMap;K.YAMLSeq=cR.YAMLSeq;K.CST=lR;K.Lexer=uR.Lexer;K.LineCounter=dR.LineCounter;K.Parser=fR.Parser;K.parse=Qo.parse;K.parseAllDocuments=Qo.parseAllDocuments;K.parseDocument=Qo.parseDocument;K.stringify=Qo.stringify;K.visit=Dm.visit;K.visitAsync=Dm.visitAsync});import{promises as xj}from"fs";import we from"path";import vr from"path";import{isDeepStrictEqual as uI}from"util";import{createHash as DN}from"crypto";function zf(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 Wf(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Wf(e[t]);return Object.freeze(e)}function oi(e){return Wf(structuredClone(e))}function Jc(e,t,i,n){return e.resolveStep({pkg:oi(t),state:oi(i),context:oi(n)})}function Uf(e,t,i,n,r,a){return e.resolveNext({pkg:oi(t),state:oi(i),step:oi(n),outcome:oi(r),context:oi(a)})}function MN(e,t,i){return DN("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function zc(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Kf(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=Jc(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=zc(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:MN(s.runId,s.iteration,o.id),stepId:o.id};return FN(e,s,c,i)}function FN(e,t,i,n){let r=zf(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 Gf(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"?Jc(n,e,t,r):void 0,o=a?zc(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"?Uf(n,e,t,o,i,r):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!zc(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 bd}from"fs";import Eg from"path";var Ys=Vc(Zo(),1);import{promises as mg}from"fs";import Wt from"path";import{createHash as vR}from"node:crypto";import{promises as mt}from"node:fs";import Ze from"node:path";import{TextDecoder as gR}from"node:util";import Pu from"path";var hR=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),pR=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function mR(e){return e.toLowerCase().startsWith(".env")}function Tt(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>mR(n))?"environment-file":i.some(n=>pR.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>hR.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Cu(e,t){let i=Tt(t);if(i)return i;let n=Pu.resolve(e.projectRoot,...t.split("/")),r=Pu.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===Pu.resolve(e.configFile)?"native-runtime":null}function gi(e){return e!==0&&e!==0n&&e!=="0"}function Ee(e,t){return gi(e.dev)&&gi(t.dev)&&gi(e.ino)&&gi(t.ino)}function L(e,t){let i=gi(e.dev)&&gi(t.dev);if(i&&e.dev!==t.dev)return!1;let n=gi(e.ino)&&gi(t.ino);return n&&e.ino!==t.ino?!1:i&&n?!0:e.birthtime===t.birthtime}var Qr=1024*1024;function Au(e,t){let i=Ze.relative(e,t);return i===""||!Ze.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ze.sep}`)}function wR(e){let t=Ze.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})||Ze.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=Tt(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 yR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function NR(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function es(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Mm(e){let t=await mt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await mt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function bR(e,t){let i=Ze.resolve(e),n=Ze.resolve(t);if(!Au(i,n))throw new Error("Native artifact path is outside its root");let r=[await Mm(i)],a=i;for(let o of Ze.relative(i,n).split(Ze.sep).filter(Boolean)){a=Ze.join(a,o);let s=await Mm(a);if(!Au(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Fm(e){for(let t of e){let i=await mt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!NR(t,i)||await mt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function _e(e){let t=wR(e.ref),i=yR(e.maxBytes??Qr),n=Ze.resolve(e.root,...t.split("/")),r=await bR(e.root,Ze.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await mt.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 mt.realpath(n);if(!Au(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await mt.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),mt.lstat(n),mt.realpath(n)]);if(await Fm(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!es(a,c)||!es(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 S=i+1-f,k=await s.read(p,0,Math.min(p.length,S),null);if(k.bytesRead===0)break;if(f+=k.bytesRead,f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),mt.lstat(n),mt.realpath(n)]);if(await Fm(r),!h.isFile()||h.isSymbolicLink()||v!==o||!es(c,m)||!es(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let N=Buffer.concat(d,f),b;try{b=new gR("utf-8",{fatal:!0}).decode(N)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:vR("sha256").update(N).digest("hex"),text:b}}finally{await s.close()}}import{randomUUID as SR}from"crypto";import{promises as Re}from"fs";import vt from"path";function Tu(e,t){let i=vt.relative(e,t);return i===""||!vt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${vt.sep}`)}function kR(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xu(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Lm(e){let t=await Re.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 Re.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Zr(e){for(let t of e){let i=await Re.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!kR(t,i)||await Re.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function ER(e,t){let i=vt.resolve(e),n=vt.resolve(t);if(!Tu(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let r=[await Lm(i)],a=vt.relative(i,n).split(vt.sep).filter(Boolean),o=i;for(let s of a){await Zr(r),o=vt.join(o,s);try{await Re.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Lm(o);if(!Tu(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Zr(r),r}async function RR(e){let t;try{t=await Re.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 qm(e,t,i={}){let n=vt.dirname(e),r=i.containedRoot?await ER(i.containedRoot,n):null;r||await Re.mkdir(n,{recursive:!0});let a=vt.join(n,`.${vt.basename(e)}.${SR()}.tmp`),o,s;try{if(await i.beforeTemporaryOpen?.(),o=await Re.open(a,"wx"),s=await o.stat(),r){let[c,l]=await Promise.all([Re.lstat(a),Re.realpath(a)]);if(await Zr(r),!c.isFile()||c.isSymbolicLink()||!xu(s,c)||!Tu(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(),!xu(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 Zr(r);let c=await Re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!xu(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Re.link(a,e),await Re.unlink(a)):await Re.rename(a,e),await RR(n)}catch(c){if(await o?.close(),!r)await Re.rm(a,{force:!0});else try{await Zr(r),await Re.rm(a,{force:!0})}catch{}throw c}}async function Le(e,t,i={}){await qm(e,t,i)}async function Bm(e,t,i={}){await qm(e,t,i)}async function pe(e,t,i={}){await Le(e,JSON.stringify(t,null,2)+`
|
|
143
|
+
`,i)}import zR from"path";var ta=Vc(Zo(),1);import is from"path";var as=64*1024,ns=1024,rs=64,Jm=5,PR=[".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/**"],gt={include:["**/*"],exclude:[...PR],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},ts={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,47 +161,47 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
161
161
|
# 可选值:true | false`}};function zm(e,t){return ts[t][e]}function CR(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 ts.en)return a;if(r===2&&t){let o=`${t}.${a}`;if(o in ts.en)return o}if(r===4&&t==="native"&&i==="snapshot"){let o=`native.snapshot.${a}`;if(o in ts.en)return o}return null}function os(e,t){let i=[],n=null,r=null;for(let a of(0,ta.stringify)(e).trimEnd().split(`
|
|
162
162
|
`)){let o=CR(a,n,r);if(o){let s=a.match(/^\s*/u)?.[0]??"";for(let c of zm(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 AR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||is.posix.isAbsolute(i)||is.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 $n(e){let t=AR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Wm(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 Iu(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||is.posix.isAbsolute(n)||is.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 ea(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Um(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 ss(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>ns)throw new Error(`${t} exceeds ${ns} 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>rs)throw new Error(`${t} contains more than ${rs} wildcard tokens`);return e}function Vm(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=>ss(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function _u(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 xR(e){if(e===void 0)return{...gt,include:[...gt.include],exclude:[...gt.exclude]};let t=ea(e,"native.snapshot");return{include:Vm(t.include,"native.snapshot.include",gt.include),exclude:Vm(t.exclude,"native.snapshot.exclude",gt.exclude),max_files:_u(t.max_files,gt.max_files,"native.snapshot.max_files"),max_total_bytes:_u(t.max_total_bytes,gt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:_u(t.max_duration_ms,gt.max_duration_ms,"native.snapshot.max_duration_ms")}}function TR(e){if(e===void 0)return;let t=ea(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=ea(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:$n(n),toArtifactRoot:$n(r),stage:a,...o?{cleanup:o}:{}}}function _R(e){let t=ea(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??Jm;if(!Number.isSafeInteger(r)||r<1)throw new Error("native.max_verify_failures must be a positive integer");let a=TR(t.pending_root_move);return{artifact_root:$n(t.artifact_root),language:Um(t.language,"en","native.language"),clarification_mode:i,archive_confirmation:n,max_verify_failures:r,snapshot:xR(t.snapshot),...a?{pending_root_move:a}:{}}}function IR(e){let t=ea(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:Wm(t.artifact_layout),language:Um(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function jR(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function OR(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 ia(e,t={}){let i=(0,ta.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=jR(r.ambient_resume),o=r.native===void 0?void 0:_R(r.native),s=r.classic===void 0?void 0:IR(r.classic),c=OR(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Km(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 Gm(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:Km(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 On(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function cs(e,t){let i=Gm(t),n=ia((0,ta.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=On(e.native),o=On(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=On(a.pending_root_move),l=Km(n.native.pending_root_move),u=On(c.cleanup),d=On(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={...On(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}import{createHash as HR}from"crypto";import{promises as ds}from"fs";import wi from"path";import{constants as ls,promises as en}from"fs";var wt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function ju(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ym(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function na(e){return{dev:e.dev,ino:e.ino,birthtime:ju(e)}}function us(e,t){let i=na(e),n=na(t);return Ee(i,n)?L(i,n):L(i,n)&&ju(e)===ju(t)&&Ym(e)===Ym(t)&&e.size===t.size}async function tn(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 en.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new wt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new wt("too-large",`${n} exceeds ${t} bytes`);let o=await en.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:na(a)});let s=process.platform==="win32"?ls.O_RDONLY:ls.O_RDONLY|ls.O_NOFOLLOW|ls.O_NONBLOCK,c;try{c=await en.open(e,s)}catch(l){throw l.code==="ELOOP"?new wt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),en.lstat(e,{bigint:r}),en.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!us(a,l)||!us(a,u))throw new wt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:na(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-p,{bytesRead:S}=await c.read(m,0,Math.min(m.length,b),null);if(S===0)break;if(p+=S,p>t)throw new wt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([c.stat({bigint:r}),en.lstat(e,{bigint:r}),en.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||N!==o||!us(a,h)||!us(a,v))throw new wt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:na(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function $R(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ou(e,t){let i=wi.relative(e,t);return i===""||!wi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${wi.sep}`)}async function Xm(e,t){let i=wi.resolve(e),n=await ds.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ds.realpath(i)}async function Qm(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=wi.join(r,i[a]);let o;try{o=await ds.lstat(r)}catch(u){if($R(u))return{exists:!1,kind:"missing"};throw u}let s=wi.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 ds.realpath(r);if(!Ou(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 ra(e,t,i){let n=Iu(t,i.label),r=wi.resolve(e),a=await Xm(r,i.label),o=n.split("/"),s=wi.resolve(r,...o);if(!Ou(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Qm(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Hn(e,t,i,n){let r=await ra(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 Xm(r.projectRoot,n.label);return tn(r.target,i,{...n,verify:async(o,s)=>{if(!Ou(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Qm(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var aa=".comet/config.yaml";function $u(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function DR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Hu(e,t={}){return(await oa(e,t)).document}async function Zm(e){try{return(await Hn(e,aa,as,{label:aa})).bytes}catch(t){if(DR(t))return null;throw t}}function ev(e){return e?{exists:!0,sha256:HR("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fs(e){return ev(await Zm(e))}async function oa(e,t={}){let i=await Zm(e);return{document:i?ia(i.toString("utf8"),t):null,identity:ev(i)}}var X$=16*1024;async function Mu(e,t){if(!t)return;let i=await fs(e);if(!$u(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as Dn}from"fs";import X from"path";import LR from"os";var hs=".comet/config.yaml";async function Fu(e){try{return await Dn.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qR(e){try{let t=await Dn.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sa(e,t){let i=X.relative(e,t);return i===""||!X.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${X.sep}`)}async function ca(e){let t=[],i=e;for(;!await Fu(i);){let r=X.dirname(i);if(r===i)break;t.push(X.basename(i)),i=r}let n=await Dn.realpath(i);return X.resolve(n,...t.reverse())}async function tv(e){try{return(await Dn.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lu(e){let t=X.resolve(e);try{(await Dn.stat(t)).isDirectory()||(t=X.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=X.resolve(LR.homedir());for(;;){if(!(t===n&&i!==n)){let o=X.join(t,...hs.split("/")),s=t===i||await qR(o);if(await Fu(o)&&s)return t}if(await Fu(X.join(t,".git")))return t;let a=X.dirname(t);if(a===t)return i;t=a}}function ps(e){return $n(e)}async function BR(e,t){let i=ps(t),n=X.resolve(e,...i.split("/")),r=await Dn.realpath(e),a=await ca(n);if(!sa(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function _t(e,t){let i=ps(t),n=await BR(e,i),r=X.join(n,"comet");if(await tv(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ca(n),ca(r)]);if(!sa(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:X.resolve(e),configFile:X.join(e,...hs.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:X.join(r,"specs"),changesDir:X.join(r,"changes"),archiveDir:X.join(r,"archive"),runtimeDir:X.join(r,"runtime"),locksDir:X.join(r,"runtime","locks"),transactionsDir:X.join(r,"runtime","transactions")}}function B(e,t){return sa(X.resolve(e),X.resolve(t))}async function I(e,t){let i=X.resolve(e),n=X.resolve(t);if(!sa(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await tv(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([ca(i),ca(n)]);if(!sa(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var qu=gt;var ms=ss;async function qe(e){let t=(await Hu(e))?.config??null;return t?.native?t:null}async function Mn(e){let t=await qe(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 la(e,t,i={}){let n=await oa(e,{allowPartialProject:!0}),r=cs(n.document?.value??{},t),a=JR.join(e,...hs.split("/"));await Le(a,os(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Mu(e,n.identity)}})}import{promises as PP}from"fs";import CP from"path";import{AsyncLocalStorage as zR}from"async_hooks";import{randomUUID as rv}from"crypto";import{promises as et}from"fs";import av from"os";import ae from"path";var iv=16*1024,Bu=".coordinator",WR=5e3,nv=new zR,vs=new Map;function UR(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function KR(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 ov(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 Vu(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ee(i,n)?L(i,n):L(i,n)&&e.size===t.size}function gs(e,t){return Vu(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function GR(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&&gs(e.identity,t.identity)}async function It(e){let t,i;try{let n=await tn(e,iv,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof wt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${iv} 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:KR(JSON.parse(t.toString("utf8")),e),identity:ov(i)}}async function YR(e){return(await It(e))?.owner??null}function Ju(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==av.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=iP(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function XR(e,t){try{await et.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await et.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ws(e,t){let i=await It(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!gs(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await et.mkdir(t,{recursive:!0});let n=ae.join(t,`${ae.basename(e.file)}.${e.owner.id}.${rv()}.removed`);try{await et.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await It(n);if(!r||r.owner.id!==e.owner.id||!Vu(r.identity,e.identity))throw await XR(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await et.rm(n,{force:!0}),"removed"}function sv(e){return{id:rv(),pid:process.pid,hostname:av.hostname(),createdAt:new Date().toISOString(),operation:e}}async function cv(e,t){let i;try{i=await et.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await YR(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(),ov(await i.stat({bigint:!0}))}finally{await i.close()}}async function QR(e,t){let i=await I(e.nativeRoot,e.locksDir);await et.mkdir(i,{recursive:!0});let n=await I(e.nativeRoot,ae.join(i,Bu));await et.mkdir(n,{recursive:!0});let r=sv(t),a=ae.join(n,`.${r.id}.tmp`),o=ae.join(n,`${r.id}.claim`);try{let s=await cv(a,r);await et.rename(a,o);let c=await It(o);if(!c||!Vu(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 et.rm(a,{force:!0})}}async function ZR(e){let t=ae.dirname(e.file),i=!1,n=ae.basename(e.file);for(let r of await et.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ae.join(t,r.name);if(ae.resolve(a)!==ae.resolve(e.file))try{let o=await It(a),s=Ju(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ws(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function lv(e){let t=await It(e.file);if(t){if(t.owner.id!==e.owner.id||!gs(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ws(t,ae.dirname(e.file))}}async function eP(e,t){let i=Date.now()+WR;for(;;){let n=await QR(e,t);if(!await ZR(n))return n;if(await lv(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 tP(e){let t=vs.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return vs.set(e,r),await t,()=>{i(),vs.get(e)===r&&vs.delete(e)}}async function ys(e,t,i){let n=ae.resolve(e.locksDir),r=nv.getStore();if(r?.has(n))return i();let a=await tP(n);try{let o=await eP(e,t),s=new Map(r??[]);return s.set(n,o),await nv.run(s,async()=>{try{return await i()}finally{await lv(o)}})}finally{a()}}async function Ns(e,t,i){let n=[...new Map(e.map(a=>[ae.resolve(a.locksDir),a])).values()].sort((a,o)=>ae.resolve(a.locksDir).localeCompare(ae.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?ys(o,t,()=>r(a+1)):i()};return r(0)}async function yi(e,t,i){return ys(e,`acquire ${t}`,async()=>{let n=await I(e.nativeRoot,e.locksDir);await et.mkdir(n,{recursive:!0});let r=await I(e.nativeRoot,ae.join(n,UR(t))),a=sv(i),o=await cv(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Ni(e){await It(e.file)&&await ys(e,`release ${ae.basename(e.file)}`,async()=>{let t=await It(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!gs(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ae.join(e.locksDir,Bu);await ws(t,i)})}function iP(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function ua(e){return Ju(await It(e))}async function zu(e,t,i){return ys(e,`take over ${ae.basename(t)}`,async()=>{let n=await I(e.nativeRoot,e.locksDir),r=await I(e.nativeRoot,t);if(ae.resolve(ae.dirname(r))!==ae.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await It(r),o=Ju(a);if(o.status==="missing")return{status:"missing"};if(i&&!GR(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=ae.join(n,Bu);return await ws(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as da}from"fs";import tt from"path";import{TextDecoder as sP}from"util";import{createHash as nP}from"node:crypto";import{constants as bs,promises as q}from"node:fs";import W from"node:path";import{TextDecoder as rP}from"node:util";function Pe(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}function uv(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Ln(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,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&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function bi(e,t){let i=await q.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await q.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Si(e,t,i){let n=W.resolve(e),r=W.resolve(t);if(!Pe(n,r))throw new Error(`${i} is outside its managed root`);let a=[await bi(n,i)],o=n;for(let s of W.relative(n,r).split(W.sep).filter(Boolean)){await se(a,i),o=W.join(o,s);let c=await bi(o,i);if(!Pe(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await se(a,i),a}async function se(e,t){for(let i of e){let n=await q.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Ln(i,n)||await q.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function aP(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 ee(e){let t=uv(e.maxBytes),i=W.resolve(e.file),n=await Si(e.root,W.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>bi(W.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await se(n,e.label);let a=await q.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=dv(a),s=await q.realpath(i);if(!Pe(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Pe(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?bs.O_RDONLY:bs.O_RDONLY|bs.O_NOFOLLOW|bs.O_NONBLOCK,l=await q.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([q.lstat(i),q.realpath(i)]);if(await se(n,e.label),await se(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Fn(o,u)||!Fn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await aP(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),q.lstat(i),q.realpath(i)]);if(await se(n,e.label),await se(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Fn(o,m)||!Fn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:nP("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Ss(e){let t=await ee(e),i;try{i=new rP("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 Ue(e){let t=await Si(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await q.readdir(e.directory,{withFileTypes:!0});else{let n=uv(e.maxEntries);i=[];let r=await q.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 se(t,e.label),{entries:i,verify:()=>se(t,e.label)}}async function ki(e){let t=await Si(e.root,e.directory,e.label);return{verify:()=>se(t,e.label)}}async function oP(e){let t=W.resolve(e.directory),i=W.resolve(e.quarantine);if(W.dirname(i)!==W.dirname(t)||!Pe(W.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await Si(e.root,W.dirname(t),e.label),r=await bi(t,e.label);if(!Pe(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await se(n,e.label);let a=await q.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Ln(r,a)||await q.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await q.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await q.rename(t,i),await se(n,e.label);let o=await q.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Ln(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await q.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 fv(e){await oP(e)}async function ks(e){let t=W.resolve(e.file),i=await Si(e.root,W.dirname(t),e.label),n=await q.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=dv(n),a=await q.realpath(t);if(!Pe(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ee({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([q.lstat(t),q.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Fn(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await se(i,e.label);let[l,u]=await Promise.all([q.lstat(t),q.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Fn(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await q.rm(t),await se(i,e.label)}async function Wu(e){let t=W.resolve(e.directory),i=await Si(e.root,W.dirname(t),e.label),n=await bi(t,e.label);if(!Pe(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await se(i,e.label);let r=await q.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Ln(n,r)||await q.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await q.rmdir(t),await se(i,e.label)}async function jt(e){let t=W.resolve(e.root),i=W.resolve(e.directory);if(!Pe(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await bi(t,e.label)],r=t;for(let a of W.relative(t,i).split(W.sep).filter(Boolean)){await se(n,e.label),r=W.join(r,a);try{await q.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await bi(r,e.label);if(!Pe(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await se(n,e.label)}async function Uu(e){let t=W.resolve(e.root),i=W.resolve(e.source),n=W.resolve(e.target);if(i===n||!Pe(t,i)||!Pe(t,n)||Pe(i,n)||Pe(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await jt({root:t,directory:W.dirname(n),label:`${e.label} target parent`});let r=await Si(t,W.dirname(i),e.label),a=await Si(t,W.dirname(n),e.label),o=await bi(i,e.label);if(!Pe(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await q.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([se(r,e.label),se(a,e.label)]);let s=await q.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Ln(o,s)||await q.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await q.rename(i,n),await Promise.all([se(r,e.label),se(a,e.label)]);let c=await q.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Ln(o,c)||!Pe(r[0].realPath,await q.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await q.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ei(e){let t=await ee({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 Bm(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 q.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ee({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 ee({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 cP=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),lP=new Set(["id","type","source","target","staged","backup"]),uP=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),dP=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),fP=new Set(["sequence","timestamp","type","operationId"]),vv=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),gv=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),hP=256*1024,pP=1024*1024,wv=16*1024,Rs=1024,Yu=64*1024*1024,mP=2e4,yv=new sP("utf-8",{fatal:!0});function fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ha(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 Bn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ku(e,t){if(typeof e!="string"||e.length===0||tt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Es(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function hv(e,t){if(Ku(e,t),e.includes("\\")||e!==tt.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 vP(e,t){let i=fa(e,`transaction operations[${t}]`);if(ha(i,lP,`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`);Ku(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Ku(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 Cs(e){let t=fa(e,"Native Archive transaction journal");if(ha(t,uP,"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"||!vv.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(!Bn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Es(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=fa(s,`Archive transaction operations[${c}]`);if(ha(l,dP,`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`);hv(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&hv(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Es(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(Es(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`);Es(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 Xu(e){let t=fa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Cs(t);if(ha(t,cP,"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"||!vv.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!tt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!tt.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(!Bn(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(vP),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 Nv(e,t){let i=fa(e,`Native transaction event at line ${t}`);if(ha(i,fP,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Bn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!gv.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 gP(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&&!Bn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Bn(e)}function qn(e,t){return e.length<t.length&&t.startsWith(e)}function wP(e){let t='","operationId":"';if(qn(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)?qn(i.slice(n),'"}'):!1}function yP(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>wv)return!1;let i=`{"sequence":${t},"timestamp":"`;if(qn(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(!gP(r))return!1;if(n.length<24)return!0;if(!Bn(r))return!1;let a='","type":"',o=n.slice(24);if(qn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of gv){if(qn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(wP(l))return!0}else if(qn(l,'"}'))return!0}return!1}function NP(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>wv)throw new Error(`Native transaction event at line ${t} is too large`);return Nv(JSON.parse(e),t)}function bP(e){let t=e.split(`
|
|
166
|
-
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Rs)throw new Error(`Native transaction event log exceeds ${Rs} 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(
|
|
164
|
+
`)}function AR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||is.posix.isAbsolute(i)||is.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 $n(e){let t=AR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Wm(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 Iu(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||is.posix.isAbsolute(n)||is.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 ea(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Um(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 ss(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>ns)throw new Error(`${t} exceeds ${ns} 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>rs)throw new Error(`${t} contains more than ${rs} wildcard tokens`);return e}function Vm(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=>ss(n,t)))].sort((n,r)=>n.localeCompare(r,"en"))}function _u(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 xR(e){if(e===void 0)return{...gt,include:[...gt.include],exclude:[...gt.exclude]};let t=ea(e,"native.snapshot");return{include:Vm(t.include,"native.snapshot.include",gt.include),exclude:Vm(t.exclude,"native.snapshot.exclude",gt.exclude),max_files:_u(t.max_files,gt.max_files,"native.snapshot.max_files"),max_total_bytes:_u(t.max_total_bytes,gt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:_u(t.max_duration_ms,gt.max_duration_ms,"native.snapshot.max_duration_ms")}}function TR(e){if(e===void 0)return;let t=ea(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=ea(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:$n(n),toArtifactRoot:$n(r),stage:a,...o?{cleanup:o}:{}}}function _R(e,t={}){let i=ea(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??Jm;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=TR(i.pending_root_move);return{artifact_root:$n(n),language:Um(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:xR(i.snapshot),...s?{pending_root_move:s}:{}}}function IR(e){let t=ea(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:Wm(t.artifact_layout),language:Um(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function jR(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function OR(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 ia(e,t={}){let i=(0,ta.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=jR(r.ambient_resume),o=r.native===void 0?void 0:_R(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),s=r.classic===void 0?void 0:IR(r.classic),c=OR(r,o,s,a,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function Km(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 Gm(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:Km(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 On(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function cs(e,t){let i=Gm(t),n=ia((0,ta.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=On(e.native),o=On(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=On(a.pending_root_move),l=Km(n.native.pending_root_move),u=On(c.cleanup),d=On(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={...On(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}import{createHash as HR}from"crypto";import{promises as ds}from"fs";import wi from"path";import{constants as ls,promises as en}from"fs";var wt=class extends Error{reason;constructor(t,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=t}};function ju(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ym(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function na(e){return{dev:e.dev,ino:e.ino,birthtime:ju(e)}}function us(e,t){let i=na(e),n=na(t);return Ee(i,n)?L(i,n):L(i,n)&&ju(e)===ju(t)&&Ym(e)===Ym(t)&&e.size===t.size}async function tn(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 en.lstat(e,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new wt("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new wt("too-large",`${n} exceeds ${t} bytes`);let o=await en.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:na(a)});let s=process.platform==="win32"?ls.O_RDONLY:ls.O_RDONLY|ls.O_NOFOLLOW|ls.O_NONBLOCK,c;try{c=await en.open(e,s)}catch(l){throw l.code==="ELOOP"?new wt("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:r}),en.lstat(e,{bigint:r}),en.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!us(a,l)||!us(a,u))throw new wt("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:na(l)}),await i.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let b=t+1-p,{bytesRead:S}=await c.read(m,0,Math.min(m.length,b),null);if(S===0)break;if(p+=S,p>t)throw new wt("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,S)))}await i.hooks?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([c.stat({bigint:r}),en.lstat(e,{bigint:r}),en.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||N!==o||!us(a,h)||!us(a,v))throw new wt("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:N,identity:na(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:N}}finally{await c.close()}}function $R(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ou(e,t){let i=wi.relative(e,t);return i===""||!wi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${wi.sep}`)}async function Xm(e,t){let i=wi.resolve(e),n=await ds.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ds.realpath(i)}async function Qm(e,t,i,n){let r=e;for(let a=0;a<i.length;a++){r=wi.join(r,i[a]);let o;try{o=await ds.lstat(r)}catch(u){if($R(u))return{exists:!1,kind:"missing"};throw u}let s=wi.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 ds.realpath(r);if(!Ou(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 ra(e,t,i){let n=Iu(t,i.label),r=wi.resolve(e),a=await Xm(r,i.label),o=n.split("/"),s=wi.resolve(r,...o);if(!Ou(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Qm(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Hn(e,t,i,n){let r=await ra(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 Xm(r.projectRoot,n.label);return tn(r.target,i,{...n,verify:async(o,s)=>{if(!Ou(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Qm(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var aa=".comet/config.yaml";function $u(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function DR(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Hu(e,t={}){return(await oa(e,t)).document}async function Zm(e){try{return(await Hn(e,aa,as,{label:aa})).bytes}catch(t){if(DR(t))return null;throw t}}function ev(e){return e?{exists:!0,sha256:HR("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fs(e){return ev(await Zm(e))}async function oa(e,t={}){let i=await Zm(e);return{document:i?ia(i.toString("utf8"),t):null,identity:ev(i)}}var Q$=16*1024;async function Mu(e,t){if(!t)return;let i=await fs(e);if(!$u(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{promises as Dn}from"fs";import X from"path";import qR from"os";var hs=".comet/config.yaml";async function Fu(e){try{return await Dn.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function BR(e){try{let t=await Dn.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sa(e,t){let i=X.relative(e,t);return i===""||!X.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${X.sep}`)}async function ca(e){let t=[],i=e;for(;!await Fu(i);){let r=X.dirname(i);if(r===i)break;t.push(X.basename(i)),i=r}let n=await Dn.realpath(i);return X.resolve(n,...t.reverse())}async function tv(e){try{return(await Dn.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lu(e){let t=X.resolve(e);try{(await Dn.stat(t)).isDirectory()||(t=X.dirname(t))}catch(r){if(r.code!=="ENOENT")throw r}let i=t,n=X.resolve(qR.homedir());for(;;){if(!(t===n&&i!==n)){let o=X.join(t,...hs.split("/")),s=t===i||await BR(o);if(await Fu(o)&&s)return t}if(await Fu(X.join(t,".git")))return t;let a=X.dirname(t);if(a===t)return i;t=a}}function ps(e){return $n(e)}async function VR(e,t){let i=ps(t),n=X.resolve(e,...i.split("/")),r=await Dn.realpath(e),a=await ca(n);if(!sa(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function _t(e,t){let i=ps(t),n=await VR(e,i),r=X.join(n,"comet");if(await tv(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ca(n),ca(r)]);if(!sa(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:X.resolve(e),configFile:X.join(e,...hs.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:X.join(r,"specs"),changesDir:X.join(r,"changes"),archiveDir:X.join(r,"archive"),runtimeDir:X.join(r,"runtime"),locksDir:X.join(r,"runtime","locks"),transactionsDir:X.join(r,"runtime","transactions")}}function B(e,t){return sa(X.resolve(e),X.resolve(t))}async function I(e,t){let i=X.resolve(e),n=X.resolve(t);if(!sa(i,n))throw new Error(`Path is outside the Native root: ${t}`);if(await tv(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[r,a]=await Promise.all([ca(i),ca(n)]);if(!sa(r,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var qu=gt;var ms=ss;async function qe(e){let t=(await Hu(e))?.config??null;return t?.native?t:null}async function Mn(e){let t=await qe(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 la(e,t,i={}){let n=await oa(e,{allowPartialProject:!0}),r=cs(n.document?.value??{},t),a=zR.join(e,...hs.split("/"));await Le(a,os(r,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await Mu(e,n.identity)}})}import{promises as CP}from"fs";import AP from"path";import{AsyncLocalStorage as WR}from"async_hooks";import{randomUUID as rv}from"crypto";import{promises as et}from"fs";import av from"os";import ae from"path";var iv=16*1024,Bu=".coordinator",UR=5e3,nv=new WR,vs=new Map;function KR(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function GR(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 ov(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 Vu(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ee(i,n)?L(i,n):L(i,n)&&e.size===t.size}function gs(e,t){return Vu(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function YR(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&&gs(e.identity,t.identity)}async function It(e){let t,i;try{let n=await tn(e,iv,{bigint:!0,label:"Native lock"});t=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof wt?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${iv} 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:GR(JSON.parse(t.toString("utf8")),e),identity:ov(i)}}async function XR(e){return(await It(e))?.owner??null}function Ju(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==av.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=nP(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function QR(e,t){try{await et.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await et.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ws(e,t){let i=await It(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!gs(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await et.mkdir(t,{recursive:!0});let n=ae.join(t,`${ae.basename(e.file)}.${e.owner.id}.${rv()}.removed`);try{await et.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await It(n);if(!r||r.owner.id!==e.owner.id||!Vu(r.identity,e.identity))throw await QR(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await et.rm(n,{force:!0}),"removed"}function sv(e){return{id:rv(),pid:process.pid,hostname:av.hostname(),createdAt:new Date().toISOString(),operation:e}}async function cv(e,t){let i;try{i=await et.open(e,"wx")}catch(n){if(n.code==="EEXIST"){let r=await XR(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(),ov(await i.stat({bigint:!0}))}finally{await i.close()}}async function ZR(e,t){let i=await I(e.nativeRoot,e.locksDir);await et.mkdir(i,{recursive:!0});let n=await I(e.nativeRoot,ae.join(i,Bu));await et.mkdir(n,{recursive:!0});let r=sv(t),a=ae.join(n,`.${r.id}.tmp`),o=ae.join(n,`${r.id}.claim`);try{let s=await cv(a,r);await et.rename(a,o);let c=await It(o);if(!c||!Vu(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 et.rm(a,{force:!0})}}async function eP(e){let t=ae.dirname(e.file),i=!1,n=ae.basename(e.file);for(let r of await et.readdir(t,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ae.join(t,r.name);if(ae.resolve(a)!==ae.resolve(e.file))try{let o=await It(a),s=Ju(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ws(o,t);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function lv(e){let t=await It(e.file);if(t){if(t.owner.id!==e.owner.id||!gs(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ws(t,ae.dirname(e.file))}}async function tP(e,t){let i=Date.now()+UR;for(;;){let n=await ZR(e,t);if(!await eP(n))return n;if(await lv(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 iP(e){let t=vs.get(e)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=t.then(()=>n);return vs.set(e,r),await t,()=>{i(),vs.get(e)===r&&vs.delete(e)}}async function ys(e,t,i){let n=ae.resolve(e.locksDir),r=nv.getStore();if(r?.has(n))return i();let a=await iP(n);try{let o=await tP(e,t),s=new Map(r??[]);return s.set(n,o),await nv.run(s,async()=>{try{return await i()}finally{await lv(o)}})}finally{a()}}async function Ns(e,t,i){let n=[...new Map(e.map(a=>[ae.resolve(a.locksDir),a])).values()].sort((a,o)=>ae.resolve(a.locksDir).localeCompare(ae.resolve(o.locksDir))),r=async a=>{let o=n[a];return o?ys(o,t,()=>r(a+1)):i()};return r(0)}async function yi(e,t,i){return ys(e,`acquire ${t}`,async()=>{let n=await I(e.nativeRoot,e.locksDir);await et.mkdir(n,{recursive:!0});let r=await I(e.nativeRoot,ae.join(n,KR(t))),a=sv(i),o=await cv(r,a);return{file:r,nativeRoot:e.nativeRoot,locksDir:n,owner:a,identity:o}})}async function Ni(e){await It(e.file)&&await ys(e,`release ${ae.basename(e.file)}`,async()=>{let t=await It(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!gs(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=ae.join(e.locksDir,Bu);await ws(t,i)})}function nP(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function ua(e){return Ju(await It(e))}async function zu(e,t,i){return ys(e,`take over ${ae.basename(t)}`,async()=>{let n=await I(e.nativeRoot,e.locksDir),r=await I(e.nativeRoot,t);if(ae.resolve(ae.dirname(r))!==ae.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await It(r),o=Ju(a);if(o.status==="missing")return{status:"missing"};if(i&&!YR(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=ae.join(n,Bu);return await ws(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as da}from"fs";import tt from"path";import{TextDecoder as cP}from"util";import{createHash as rP}from"node:crypto";import{constants as bs,promises as q}from"node:fs";import W from"node:path";import{TextDecoder as aP}from"node:util";function Pe(e,t){let i=W.relative(e,t);return i===""||!W.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${W.sep}`)}function uv(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Ln(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function dv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,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&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function bi(e,t){let i=await q.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await q.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function Si(e,t,i){let n=W.resolve(e),r=W.resolve(t);if(!Pe(n,r))throw new Error(`${i} is outside its managed root`);let a=[await bi(n,i)],o=n;for(let s of W.relative(n,r).split(W.sep).filter(Boolean)){await se(a,i),o=W.join(o,s);let c=await bi(o,i);if(!Pe(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await se(a,i),a}async function se(e,t){for(let i of e){let n=await q.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!Ln(i,n)||await q.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function oP(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 ee(e){let t=uv(e.maxBytes),i=W.resolve(e.file),n=await Si(e.root,W.dirname(i),e.label),r=await Promise.all((e.forbiddenRoots??[]).map(u=>bi(W.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await se(n,e.label);let a=await q.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=dv(a),s=await q.realpath(i);if(!Pe(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(r.some(u=>Pe(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?bs.O_RDONLY:bs.O_RDONLY|bs.O_NOFOLLOW|bs.O_NONBLOCK,l=await q.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([q.lstat(i),q.realpath(i)]);if(await se(n,e.label),await se(r,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Fn(o,u)||!Fn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await oP(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),q.lstat(i),q.realpath(i)]);if(await se(n,e.label),await se(r,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!Fn(o,m)||!Fn(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:rP("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Ss(e){let t=await ee(e),i;try{i=new aP("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 Ue(e){let t=await Si(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await q.readdir(e.directory,{withFileTypes:!0});else{let n=uv(e.maxEntries);i=[];let r=await q.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 se(t,e.label),{entries:i,verify:()=>se(t,e.label)}}async function ki(e){let t=await Si(e.root,e.directory,e.label);return{verify:()=>se(t,e.label)}}async function sP(e){let t=W.resolve(e.directory),i=W.resolve(e.quarantine);if(W.dirname(i)!==W.dirname(t)||!Pe(W.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let n=await Si(e.root,W.dirname(t),e.label),r=await bi(t,e.label);if(!Pe(n[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await se(n,e.label);let a=await q.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Ln(r,a)||await q.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await q.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await q.rename(t,i),await se(n,e.label);let o=await q.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Ln(r,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await q.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 fv(e){await sP(e)}async function ks(e){let t=W.resolve(e.file),i=await Si(e.root,W.dirname(t),e.label),n=await q.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=dv(n),a=await q.realpath(t);if(!Pe(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ee({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([q.lstat(t),q.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Fn(r,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await se(i,e.label);let[l,u]=await Promise.all([q.lstat(t),q.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Fn(r,l)||u!==a)throw new Error(`${e.label} changed before removal`);await q.rm(t),await se(i,e.label)}async function Wu(e){let t=W.resolve(e.directory),i=await Si(e.root,W.dirname(t),e.label),n=await bi(t,e.label);if(!Pe(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await se(i,e.label);let r=await q.lstat(t);if(!r.isDirectory()||r.isSymbolicLink()||!Ln(n,r)||await q.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before removal`);await q.rmdir(t),await se(i,e.label)}async function jt(e){let t=W.resolve(e.root),i=W.resolve(e.directory);if(!Pe(t,i))throw new Error(`${e.label} is outside its managed root`);let n=[await bi(t,e.label)],r=t;for(let a of W.relative(t,i).split(W.sep).filter(Boolean)){await se(n,e.label),r=W.join(r,a);try{await q.mkdir(r)}catch(s){if(s.code!=="EEXIST")throw s}let o=await bi(r,e.label);if(!Pe(n[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${r}`);n.push(o)}await se(n,e.label)}async function Uu(e){let t=W.resolve(e.root),i=W.resolve(e.source),n=W.resolve(e.target);if(i===n||!Pe(t,i)||!Pe(t,n)||Pe(i,n)||Pe(n,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await jt({root:t,directory:W.dirname(n),label:`${e.label} target parent`});let r=await Si(t,W.dirname(i),e.label),a=await Si(t,W.dirname(n),e.label),o=await bi(i,e.label);if(!Pe(r[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await q.lstat(n),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([se(r,e.label),se(a,e.label)]);let s=await q.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Ln(o,s)||await q.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await q.rename(i,n),await Promise.all([se(r,e.label),se(a,e.label)]);let c=await q.lstat(n);if(!c.isDirectory()||c.isSymbolicLink()||!Ln(o,c)||!Pe(r[0].realPath,await q.realpath(n)))throw new Error(`${e.label} source identity changed while moving`);try{throw await q.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Ei(e){let t=await ee({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 Bm(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 q.lstat(e.target)}catch(r){if(r.code==="ENOENT")return;throw r}throw new Error(`${e.label} target changed before commit`)}if((await ee({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 ee({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 lP=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),uP=new Set(["id","type","source","target","staged","backup"]),dP=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),fP=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),hP=new Set(["sequence","timestamp","type","operationId"]),vv=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),gv=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),pP=256*1024,mP=1024*1024,wv=16*1024,Rs=1024,Yu=64*1024*1024,vP=2e4,yv=new cP("utf-8",{fatal:!0});function fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ha(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 Bn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ku(e,t){if(typeof e!="string"||e.length===0||tt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Es(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function hv(e,t){if(Ku(e,t),e.includes("\\")||e!==tt.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 gP(e,t){let i=fa(e,`transaction operations[${t}]`);if(ha(i,uP,`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`);Ku(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&Ku(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 Cs(e){let t=fa(e,"Native Archive transaction journal");if(ha(t,dP,"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"||!vv.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(!Bn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Es(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=fa(s,`Archive transaction operations[${c}]`);if(ha(l,fP,`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`);hv(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&hv(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Es(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(Es(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`);Es(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 Xu(e){let t=fa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Cs(t);if(ha(t,lP,"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"||!vv.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!tt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!tt.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(!Bn(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(gP),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 Nv(e,t){let i=fa(e,`Native transaction event at line ${t}`);if(ha(i,hP,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Bn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!gv.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 wP(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&&!Bn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Bn(e)}function qn(e,t){return e.length<t.length&&t.startsWith(e)}function yP(e){let t='","operationId":"';if(qn(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)?qn(i.slice(n),'"}'):!1}function NP(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>wv)return!1;let i=`{"sequence":${t},"timestamp":"`;if(qn(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(!wP(r))return!1;if(n.length<24)return!0;if(!Bn(r))return!1;let a='","type":"',o=n.slice(24);if(qn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of gv){if(qn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(yP(l))return!0}else if(qn(l,'"}'))return!0}return!1}function bP(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>wv)throw new Error(`Native transaction event at line ${t} is too large`);return Nv(JSON.parse(e),t)}function SP(e){let t=e.split(`
|
|
166
|
+
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Rs)throw new Error(`Native transaction event log exceeds ${Rs} 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(bP(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&NP(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return n}function bv(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
167
167
|
`)}
|
|
168
|
-
`}function SP(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return tt.join(e.transactionsDir,t)}function As(e,t){let i=SP(e,t);return{directory:i,journal:tt.join(i,"transaction.json"),events:tt.join(i,"events.jsonl"),staged:tt.join(i,"staged"),backups:tt.join(i,"backups")}}async function Ot(e,t){let i=As(e,t);return await Promise.all(Object.values(i).map(n=>I(e.nativeRoot,n))),i}function kP(e,t){if(t.length===0||tt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=tt.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!B(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function Ri(e,t){return I(e.nativeRoot,kP(e,t))}async function nn(e){try{return await da.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Qu(e,t,i={}){let n=await Ot(e,t);try{await da.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 ee({root:e.nativeRoot,file:n.events,maxBytes:pP,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=yv.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=bP(a),s=bv(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 pv(e,t,i){let n=await Qu(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 it(e,t,i,n){let r=await Ot(e,t),a=await Qu(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await Le(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>pv(e,t,a)}),o;if(a.events.length>=Rs)throw new Error(`Native transaction event log ${t} exceeds ${Rs} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return Nv(s,s.sequence),await da.mkdir(r.directory,{recursive:!0}),await Le(r.events,bv([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>pv(e,t,a)}),s}async function Sv(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Xu(t);let i=await Ot(e,t.id);await da.mkdir(i.staged,{recursive:!0}),await da.mkdir(i.backups,{recursive:!0}),await pe(i.journal,t),await it(e,t.id,"prepared")}async function Ke(e,t,i={}){let n=await Ot(e,t),r=await ee({root:e.nativeRoot,file:n.journal,maxBytes:hP,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(yv.decode(r.bytes)),o=Xu(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Pi(e,t,i={}){return(await Qu(e,t,i)).events}async function Ps(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=Xu({...t,status:i});return await pe((await Ot(e,t.id)).journal,n),n}async function Gu(e,t,i){try{return await ee({root:e.nativeRoot,file:t,maxBytes:Yu,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Zu(e,t,i,n){let r=await Gu(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await Gu(e,i,`${n} target`);await jt({root:e.nativeRoot,directory:tt.dirname(i),label:`${n} target parent`}),await Ei({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:Yu,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function kv(e,t,i){let n=await Gu(e,t,i);n&&await ks({root:e.nativeRoot,file:t,maxBytes:Yu,expectedHash:n.hash,expectedSize:n.size,label:i})}async function mv(e,t){if(!t.backup)return;let i=await Ri(e,t.target),n=await Ri(e,t.backup);!await nn(i)||await nn(n)||await Zu(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function EP(e,t){let i=await Ri(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await mv(e,t),await Zu(e,await Ri(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await mv(e,t),await kv(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 Ri(e,t.source),[r,a]=await Promise.all([nn(n),nn(i)]);if(!r&&a){await(await Ue({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:mP})).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 Uu({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function Ev(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 Ps(e,t,"applying"):t,r=await Pi(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 it(e,n.id,"operation-started",s.id),await EP(e,s),await it(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await Ke(e,n.id),n}async function RP(e,t){let i=await Ri(e,t.target),n=t.backup?await Ri(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 Ri(e,t.source);if(await nn(i)){if(await nn(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Uu({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await nn(n)?await Zu(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await kv(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function xs(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 Pi(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 Ps(e,t,"rolling-back");await it(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 RP(e,a);return await it(e,n.id,"rollback-completed"),n=await Ps(e,n,"rolled-back"),n}async function Vn(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 it(e,t.id,i),i==="commit"?Ps(e,t,"committed"):t}async function AP(e,t){let i;try{i=await PP.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 Ke(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function xP(e,t){let i=Date.now()+5e3,n=CP.join(e.locksDir,"root-move.lock");for(;;)try{return await yi(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await ua(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 Ie(e,t,i,n){let r=await xP(e,t);try{if(await Mn(e.projectRoot),await AP(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ni(r)}}function Rv(e){return Number.isSafeInteger(e)&&e>=1}async function Pv(e){if(!Rv(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(!Rv(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 $s}from"crypto";import{spawn as Hv}from"node:child_process";import{promises as ne}from"fs";import U from"path";import{createHash as Cv}from"crypto";import{createReadStream as TP}from"fs";async function yt(e){let t=Cv("sha256");for await(let i of TP(e))t.update(i);return t.digest("hex")}function D(e){return Cv("sha256").update(e).digest("hex")}var Ts={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},od=1e3,_P=8*1024*1024,IP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),OP=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),$P=new Set(["schema","include","exclude","hash"]),HP=new Set(["provider","gitSelection","physicalSelection","projection"]),DP=new Set(["provider","selection"]),MP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),FP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),LP=new Set(["schema","status","before","after"]),qP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),BP=new Set(["path","hash","size","type","gitObjectId"]),VP=new Set(["path","size","type","reason"]),JP=new Set(["ref","hash","count"]),zP=new Set(["change-created","legacy-migration","explicit"]),WP=new Set(["file","directory","other"]),UP=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"]),Hs=/^[a-f0-9]{64}$/u,Dv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,KP=new Set(["EACCES","EPERM"]),Wn=64*1024,nd=64*1024,GP=6e4,YP=1e3,XP=2,sd={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},QP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Mv(e){let t=e.deadlineMs??GP;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 Nt(e){return Math.max(0,e.deadlineAt-Date.now())}function $(e){return Nt(e)>=1}function ed(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 va(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function ZP(e){let t={...QP,...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 eC(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&&U.win32.isAbsolute(n)?U.win32.resolve(n):"C:\\Windows",a=U.win32.join(r,"System32","taskkill.exe");if(!U.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=Hv(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),YP),u.unref()}catch{d(!1)}});for(let s=0;s<XP;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 cd(e,t,i,n){let r=Nt(e);if(r<1)throw ed();let a=e.gitProcess,o=Hv(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=eC(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?ed(m.error):ed()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Fv(e){let t={...sd,...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 Is(e,t,i,n=nd){let{child:r,completion:a}=cd(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>=Wn)return;let m=Wn-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 td(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function _s(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}=cd(e,t,i,n.stdin!==void 0),c=[],l=$s("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,N=!1,b=!1,S=k=>{let R=0;for(;R<k.byteLength;){let y=k.indexOf(0,R),w=y<0?k.byteLength:y,g=k.subarray(R,w);if(!v&&g.byteLength>0&&(h.byteLength+g.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,N=!0):h=Buffer.concat([h,g])),y<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let E=h.byteLength+1;!v&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):N=!0,h=Buffer.alloc(0),v=!1,R=y+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>n.maxBytes&&(N=!0);let R=n.outputChunkBytes;if(R===void 0){S(k);return}for(let y=0;y<k.byteLength;y+=R)S(k.subarray(y,Math.min(k.byteLength,y+R)))}),o.stderr.on("data",k=>{if(d>=Wn)return;let R=Wn-d,y=Buffer.from(k).subarray(0,R);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:R})=>{let y=n.acceptedExitCodes??[0];if(k!==null&&y.includes(k)&&R===null&&!b&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:N,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:b||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 rd(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 tC(e,t,i){if(i.length===0)return new Set;let n=await _s(e,t,["check-ignore","--no-index","-z","--stdin"],{...sd,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=rd(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function iC(e,t,i){let{child:n,completion:r}=cd(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>=Wn)return;let d=Wn-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 js(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||U.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||U.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function nC(e,t){return e.map(i=>{let n=js(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function rC(e){let t=U.resolve(e);for(;;){try{return await ne.lstat(U.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=U.dirname(t);if(i===t)return!1;t=i}}async function Lv(e,t,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await _s(e,t,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await _s(e,t,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await _s(e,t,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function qv(e){return{stageBefore:td(e.stagedBefore),combined:td(e.combined),stageAfter:td(e.stagedAfter)}}async function Bv(e,t,i=sd,n={}){if(!await rC(t))return null;let r;try{r=await Is(e,t,["rev-parse","--is-inside-work-tree"])}catch(N){throw va(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 Lv(e,t,i,n)}catch(N){throw va(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,d=new Set,f=N=>{for(let b of N){let S=rd(b),k=S.indexOf(" ");if(k<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(S.slice(0,k))?.groups;if(!R)throw new Error("Native Git snapshot provider returned a malformed staged header");let y=js(S.slice(k+1));if(y===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(y),R.stage==="0"&&u.set(y,R.objectId),R.mode==="160000"&&R.stage==="0"&&d.add(y)}};f(o.records),f(c.records);let p=s.records.map(rd),m=nC(p,"combined"),h=new Set(m.filter(N=>!l.has(N))),v=new Set(m.filter((N,b)=>!l.has(N)&&p[b].endsWith("/")));for(let N of d)v.delete(N);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:d,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:qv(a)}}function Ai(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Av(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function aC(e,t){return!Ai(e.stageBefore,e.stageAfter)||!Ai(e.stageAfter,t.stageBefore)||!Ai(e.combined,t.combined)||!Ai(t.stageBefore,t.stageAfter)}async function Vv(e,t,i,n,r){let a;try{a=await Lv(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw va(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=qv(a),c=Av(o)||Av(s),l=aC(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:D(`comet.native.git-selection-overflow.v2
|
|
169
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
168
|
+
`}function kP(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return tt.join(e.transactionsDir,t)}function As(e,t){let i=kP(e,t);return{directory:i,journal:tt.join(i,"transaction.json"),events:tt.join(i,"events.jsonl"),staged:tt.join(i,"staged"),backups:tt.join(i,"backups")}}async function Ot(e,t){let i=As(e,t);return await Promise.all(Object.values(i).map(n=>I(e.nativeRoot,n))),i}function EP(e,t){if(t.length===0||tt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i=tt.resolve(e.nativeRoot,...t.split(/[\\/]/u));if(!B(e.nativeRoot,i))throw new Error(`Unsafe Native transaction ref: ${t}`);return i}async function Ri(e,t){return I(e.nativeRoot,EP(e,t))}async function nn(e){try{return await da.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Qu(e,t,i={}){let n=await Ot(e,t);try{await da.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 ee({root:e.nativeRoot,file:n.events,maxBytes:mP,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=yv.decode(r.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=SP(a),s=bv(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 pv(e,t,i){let n=await Qu(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 it(e,t,i,n){let r=await Ot(e,t),a=await Qu(e,t),o=a.events.find(c=>c.type===i&&c.operationId===n);if(o)return a.needsRepair&&await Le(r.events,a.canonicalSource,{containedRoot:e.nativeRoot,beforeCommit:()=>pv(e,t,a)}),o;if(a.events.length>=Rs)throw new Error(`Native transaction event log ${t} exceeds ${Rs} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...n?{operationId:n}:{}};return Nv(s,s.sequence),await da.mkdir(r.directory,{recursive:!0}),await Le(r.events,bv([...a.events,s]),{containedRoot:e.nativeRoot,beforeCommit:()=>pv(e,t,a)}),s}async function Sv(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Xu(t);let i=await Ot(e,t.id);await da.mkdir(i.staged,{recursive:!0}),await da.mkdir(i.backups,{recursive:!0}),await pe(i.journal,t),await it(e,t.id,"prepared")}async function Ke(e,t,i={}){let n=await Ot(e,t),r=await ee({root:e.nativeRoot,file:n.journal,maxBytes:pP,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(yv.decode(r.bytes)),o=Xu(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Pi(e,t,i={}){return(await Qu(e,t,i)).events}async function Ps(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=Xu({...t,status:i});return await pe((await Ot(e,t.id)).journal,n),n}async function Gu(e,t,i){try{return await ee({root:e.nativeRoot,file:t,maxBytes:Yu,label:i})}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Zu(e,t,i,n){let r=await Gu(e,t,`${n} source`);if(!r)throw new Error(`${n} source does not exist`);let a=await Gu(e,i,`${n} target`);await jt({root:e.nativeRoot,directory:tt.dirname(i),label:`${n} target parent`}),await Ei({sourceRoot:e.nativeRoot,source:t,targetRoot:e.nativeRoot,target:i,maxBytes:Yu,label:n,expectedHash:r.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function kv(e,t,i){let n=await Gu(e,t,i);n&&await ks({root:e.nativeRoot,file:t,maxBytes:Yu,expectedHash:n.hash,expectedSize:n.size,label:i})}async function mv(e,t){if(!t.backup)return;let i=await Ri(e,t.target),n=await Ri(e,t.backup);!await nn(i)||await nn(n)||await Zu(e,i,n,`Legacy Native transaction backup ${t.id}`)}async function RP(e,t){let i=await Ri(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await mv(e,t),await Zu(e,await Ri(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await mv(e,t),await kv(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 Ri(e,t.source),[r,a]=await Promise.all([nn(n),nn(i)]);if(!r&&a){await(await Ue({root:e.nativeRoot,directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:vP})).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 Uu({root:e.nativeRoot,source:n,target:i,label:`Legacy Native transaction move ${t.id}`})}async function Ev(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 Ps(e,t,"applying"):t,r=await Pi(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 it(e,n.id,"operation-started",s.id),await RP(e,s),await it(e,n.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return n=await Ke(e,n.id),n}async function PP(e,t){let i=await Ri(e,t.target),n=t.backup?await Ri(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 Ri(e,t.source);if(await nn(i)){if(await nn(r))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Uu({root:e.nativeRoot,source:i,target:r,label:`Legacy Native transaction rollback move ${t.id}`})}return}n&&await nn(n)?await Zu(e,n,i,`Legacy Native transaction rollback restore ${t.id}`):await kv(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function xs(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 Pi(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 Ps(e,t,"rolling-back");await it(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 PP(e,a);return await it(e,n.id,"rollback-completed"),n=await Ps(e,n,"rolled-back"),n}async function Vn(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 it(e,t.id,i),i==="commit"?Ps(e,t,"committed"):t}async function xP(e,t){let i;try{i=await CP.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 Ke(e,n.name);if(r.id!==t&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function TP(e,t){let i=Date.now()+5e3,n=AP.join(e.locksDir,"root-move.lock");for(;;)try{return await yi(e,"root-move",t)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await ua(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 Ie(e,t,i,n){let r=await TP(e,t);try{if(await Mn(e.projectRoot),await xP(e,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await Ni(r)}}function Rv(e){return Number.isSafeInteger(e)&&e>=1}async function Pv(e){if(!Rv(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(!Rv(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 $s}from"crypto";import{spawn as Hv}from"node:child_process";import{promises as ne}from"fs";import U from"path";import{createHash as Cv}from"crypto";import{createReadStream as _P}from"fs";async function yt(e){let t=Cv("sha256");for await(let i of _P(e))t.update(i);return t.digest("hex")}function D(e){return Cv("sha256").update(e).digest("hex")}var Ts={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},od=1e3,IP=8*1024*1024,jP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OP=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$P=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),HP=new Set(["schema","include","exclude","hash"]),DP=new Set(["provider","gitSelection","physicalSelection","projection"]),MP=new Set(["provider","selection"]),FP=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),LP=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qP=new Set(["schema","status","before","after"]),BP=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),VP=new Set(["path","hash","size","type","gitObjectId"]),JP=new Set(["path","size","type","reason"]),zP=new Set(["ref","hash","count"]),WP=new Set(["change-created","legacy-migration","explicit"]),UP=new Set(["file","directory","other"]),KP=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"]),Hs=/^[a-f0-9]{64}$/u,Dv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,GP=new Set(["EACCES","EPERM"]),Wn=64*1024,nd=64*1024,YP=6e4,XP=1e3,QP=2,sd={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},ZP={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Mv(e){let t=e.deadlineMs??YP;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 Nt(e){return Math.max(0,e.deadlineAt-Date.now())}function $(e){return Nt(e)>=1}function ed(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 va(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function eC(e){let t={...ZP,...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 tC(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&&U.win32.isAbsolute(n)?U.win32.resolve(n):"C:\\Windows",a=U.win32.join(r,"System32","taskkill.exe");if(!U.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=Hv(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),XP),u.unref()}catch{d(!1)}});for(let s=0;s<QP;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 cd(e,t,i,n){let r=Nt(e);if(r<1)throw ed();let a=e.gitProcess,o=Hv(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=tC(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?ed(m.error):ed()}return{code:p,spawnError:s}});return{child:o,completion:f}}function Fv(e){let t={...sd,...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 Is(e,t,i,n=nd){let{child:r,completion:a}=cd(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>=Wn)return;let m=Wn-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 td(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function _s(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}=cd(e,t,i,n.stdin!==void 0),c=[],l=$s("sha256"),u=[],d=0,f=0,p=0,m=0,h=Buffer.alloc(0),v=!1,N=!1,b=!1,S=k=>{let R=0;for(;R<k.byteLength;){let y=k.indexOf(0,R),w=y<0?k.byteLength:y,g=k.subarray(R,w);if(!v&&g.byteLength>0&&(h.byteLength+g.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,N=!0):h=Buffer.concat([h,g])),y<0)break;m+=1,h.byteLength===0&&!v&&(b=!0);let E=h.byteLength+1;!v&&m<=n.maxRecords&&p+E<=n.maxBytes?(c.push(h),p+=E):N=!0,h=Buffer.alloc(0),v=!1,R=y+1}};o.stdout.on("data",k=>{l.update(k),f+=k.byteLength,f>n.maxBytes&&(N=!0);let R=n.outputChunkBytes;if(R===void 0){S(k);return}for(let y=0;y<k.byteLength;y+=R)S(k.subarray(y,Math.min(k.byteLength,y+R)))}),o.stderr.on("data",k=>{if(d>=Wn)return;let R=Wn-d,y=Buffer.from(k).subarray(0,R);u.push(y),d+=y.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:k,spawnError:R})=>{let y=n.acceptedExitCodes??[0];if(k!==null&&y.includes(k)&&R===null&&!b&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:N,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${R?`: ${R.message}`:b||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 rd(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 iC(e,t,i){if(i.length===0)return new Set;let n=await _s(e,t,["check-ignore","--no-index","-z","--stdin"],{...sd,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=rd(r);return a.endsWith("/")?a.slice(0,-1):a}))}async function nC(e,t,i){let{child:n,completion:r}=cd(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>=Wn)return;let d=Wn-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 js(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||U.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||U.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function rC(e,t){return e.map(i=>{let n=js(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return n})}async function aC(e){let t=U.resolve(e);for(;;){try{return await ne.lstat(U.join(t,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=U.dirname(t);if(i===t)return!1;t=i}}async function Lv(e,t,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await _s(e,t,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await _s(e,t,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await _s(e,t,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function qv(e){return{stageBefore:td(e.stagedBefore),combined:td(e.combined),stageAfter:td(e.stagedAfter)}}async function Bv(e,t,i=sd,n={}){if(!await aC(t))return null;let r;try{r=await Is(e,t,["rev-parse","--is-inside-work-tree"])}catch(N){throw va(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 Lv(e,t,i,n)}catch(N){throw va(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,d=new Set,f=N=>{for(let b of N){let S=rd(b),k=S.indexOf(" ");if(k<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(S.slice(0,k))?.groups;if(!R)throw new Error("Native Git snapshot provider returned a malformed staged header");let y=js(S.slice(k+1));if(y===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(y),R.stage==="0"&&u.set(y,R.objectId),R.mode==="160000"&&R.stage==="0"&&d.add(y)}};f(o.records),f(c.records);let p=s.records.map(rd),m=rC(p,"combined"),h=new Set(m.filter(N=>!l.has(N))),v=new Set(m.filter((N,b)=>!l.has(N)&&p[b].endsWith("/")));for(let N of d)v.delete(N);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:d,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:qv(a)}}function Ai(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Av(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function oC(e,t){return!Ai(e.stageBefore,e.stageAfter)||!Ai(e.stageAfter,t.stageBefore)||!Ai(e.combined,t.combined)||!Ai(t.stageBefore,t.stageAfter)}async function Vv(e,t,i,n,r){let a;try{a=await Lv(e,t,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw va(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=qv(a),c=Av(o)||Av(s),l=oC(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:D(`comet.native.git-selection-overflow.v2
|
|
169
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var sC=(1n<<256n)-1n;function cC(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function xv(e){let t=U.resolve(e.paths.projectRoot),i=U.resolve(e.paths.nativeRoot),n=U.resolve(e.paths.configFile),r=U.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=()=>Nt(e.execution)>=1?!0:(f=!0,m=!0,!1),v=S=>{let k=Buffer.from(`${S.type}\0${S.path}`,"utf8"),R=$s("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let y=0;y<s.length;y+=1)s[y]^=R[y];if(c=c+BigInt(`0x${R.toString("hex")}`)&sC,u+=1,d+=k.byteLength,Buffer.byteLength(S.path,"utf8")>e.limits.maxPathBytes||d>e.limits.maxBytes){f=!0,m=!0;return}a.push(S)},N=async S=>{if(m||!h())return;let k;try{k=await ne.opendir(S)}catch(E){if(!h())return;if(!de(E)&&!ue(E)||S===t&&de(E))throw E;p||=ue(E),f||=de(E),m=!0;return}if(!h()){try{await k.close()}catch(E){if(E.code!=="ERR_DIR_CLOSED")throw E}return}let R=!1,y;try{for(;!m&&h();){let E;try{E=await k.read()}catch(ie){if(!h())break;if(!de(ie)&&!ue(ie)||S===t&&de(ie))throw ie;p||=ue(ie),f||=de(ie),m=!0;break}if(!h()||E===null)break;if(l+=1,l>e.limits.maxNodes){f=!0,m=!0;break}let O=U.join(S,E.name),Z=uC(t,O);if(O===n||O===r||xi(i,O)||e.denylist.some(ie=>xi(ie,O))||Tt(Z)!==null)continue;if(!h())break;let z;try{z=await ne.lstat(O)}catch(ie){if(!h())break;if(!de(ie)&&!ue(ie))throw ie;if(p=!0,v({path:Z,type:"other"}),o.push({path:Z,size:null,type:"file",reason:de(ie)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(Z),m||!h())break;continue}if(!h())break;let Y=cC(z);if(Y==="directory"){if(pC(e.policy,Z))continue;if(!h())break;let ie;try{ie=await ne.realpath(O)}catch(Pt){if(!h())break;if(!de(Pt)&&!ue(Pt))throw Pt;if(p=!0,v({path:Z,type:Y}),o.push({path:Z,size:null,type:"directory",reason:de(Pt)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(Z),m||!h())break;continue}if(!h())break;if(!B(e.physicalProjectRoot,ie)||xi(e.physicalNativeRoot,ie))continue;if(v({path:Z,type:Y}),await e.hooks?.afterNode?.(Z),!h()||(await N(O),m))break;continue}if(v({path:Z,type:Y}),await e.hooks?.afterNode?.(Z),!h()||m)break}}catch(E){R=!0,y=E}let w;try{await k.close()}catch(E){w=E}let g=h();if(R)throw y;if(g&&w!==void 0&&w.code!=="ERR_DIR_CLOSED")throw w};await N(t),h(),f?(a.length=0,u=0,d=0):(a.sort((S,k)=>S.path.localeCompare(k.path,"en")),o.sort((S,k)=>S.path.localeCompare(k.path,"en")));let b=f?D(`comet.native.physical-selection-incomplete.v1
|
|
170
170
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):D(`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:b,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function Jv(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
|
|
172
|
-
`)}function
|
|
173
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function id(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
|
|
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:b,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:d,overflow:f,unstable:p}}}function Jv(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 lC(e,t){let i=e.overflow||t.overflow,n=e.unstable||t.unstable||!Jv(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 zv(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function Tv(e,t){let n=(await Is(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Dv.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return D(`gitlink:${n}`)}async function _v(e,t){let i=await Tv(e,t),n=await nC(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await Tv(e,t);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function pa(e,t){if(Tt(t)!==null)return!1;let i=U.resolve(e.projectRoot,...t.split("/"));return!xi(U.resolve(e.nativeRoot),i)}function ld(e,t={}){let i=Jt(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 uC(e,t){return U.relative(e,t).split(U.sep).join("/")}function dC(e,t){return t.map(i=>U.resolve(e,...i.split(/[\\/]/u)))}function xi(e,t){let i=U.resolve(e),n=U.resolve(t);return n===i||B(i,n)}function de(e){return GP.has(e.code??"")}function ue(e){return e.code==="ENOENT"}function ud(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
172
|
+
`)}function fC(e,t){return D(`comet.native.snapshot-policy.v1
|
|
173
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function id(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 hC(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Iv(e){let t=ms(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?hC(r):void 0;if(a&&!a())return!1;let o=id(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=id(i,c,a),o===null||o.size===0)return!1}return id(i,o,a)?.has(i.length)??!1}}function Wv(e){if(e===void 0)return;let t=[...new Set(e.include.map(r=>ms(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(e.exclude.map(r=>ms(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=fC(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(Iv),excludeMatchers:i.map(Iv),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 pC(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function jv(e,t,i){if(!e)return!0;let n=()=>$(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 ma(e,t,i){let n=JSON.stringify(i);return D(`${e}
|
|
174
174
|
${Buffer.byteLength(t)}:${t}
|
|
175
|
-
${Buffer.byteLength(n)}:${n}`)}function ad(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Os(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ad(i))return e.splice(t,1),i}return null}function Ci(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pC(e,t,i,n){if(!$(n))return{status:"budget-exhausted"};let r;try{r=await ne.open(e,"r")}catch(c){if(!$(n))return{status:"budget-exhausted"};throw c}if(!$(n))return await r.close(),{status:"budget-exhausted"};let a=$s("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!$(n))return{status:"budget-exhausted"};let c=await r.stat();if(!$(n))return{status:"budget-exhausted"};if(!c.isFile()||!Ci(i,c))return{status:"changed"};for(;;){if(!$(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(!$(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!$(n))return{status:"budget-exhausted"};let d=await r.stat();return $(n)?!d.isFile()||!Ci(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 nt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function rt(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function zn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function $t(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Uv(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=U.posix.normalize(e);if(i!==e||U.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function mC(e,t){let i=nt(e,`Native snapshot entry ${t}`);rt(i,BP,`Native snapshot entry ${t}`);let n=Uv(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Hs.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:$t(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Dv.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function vC(e,t){let i=nt(e,`Native snapshot omission ${t}`);if(rt(i,VP,`Native snapshot omission ${t}`),!WP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!UP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Uv(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:$t(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function gC(e){let t=nt(e,"Native snapshot omission overflow");if(rt(t,JP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hs.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:zn(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let i=nt(e,t);if(rt(i,FP,t),typeof i.hash!="string"||!Hs.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=$t(i.recordCount,`${t} recordCount`),r=$t(i.storedRecordCount,`${t} storedRecordCount`),a=$t(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 Ov(e){let t=nt(e,"Native Git selection evidence");if(rt(t,MP,"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=Jn(t.stageBefore,"Native Git selection stageBefore"),n=Jn(t.combined,"Native Git selection combined"),r=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Ai(i,r)||!Ai(r,a)||!Ai(n,o)||!Ai(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 $v(e,t){let i=nt(e,t);if(rt(i,qP,t),typeof i.hash!="string"||!Hs.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=$t(i.visitedNodeCount,`${t} visitedNodeCount`),r=$t(i.recordCount,`${t} recordCount`),a=$t(i.storedRecordCount,`${t} storedRecordCount`),o=$t(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 wC(e){let t=nt(e,"Native physical selection evidence");if(rt(t,LP,"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=$v(t.before,"Native physical selection before"),n=$v(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Jv(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 Jt(e){let t=nt(e,"Native content snapshot manifest");if(rt(t,jP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=nt(t.capture,"Native content snapshot capture");if(rt(y,HP,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:Ov(y.gitSelection),g=y.physicalSelection===void 0?void 0:wC(y.physicalSelection),E=null;if(y.projection!==void 0){let O=nt(y.projection,"Native content snapshot projection");if(rt(O,DP,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...O.selection===void 0?{}:{selection:Ov(O.selection)}}}if(y.provider==="git"){if(g||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{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=nt(t.limits,"Native content snapshot limits");rt(n,OP,"Native content snapshot limits");let r={maxFiles:zn(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:zn(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:zn(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:zn(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:zn(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=nt(t.policy,"Native snapshot policy");if(rt(y,$P,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Wv({include:y.include,exclude:y.exclude,hash:y.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(mC),s=t.omitted.map(vC),c=$t(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:gC(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>r.maxFileBytes)||o.reduce((y,w)=>y+w.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>od||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(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.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(y=>y.reason==="physical-enumeration-limit"),N=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...v,...N])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=i?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",k=b?.status==="changed"||b?.status==="overflow-and-changed";if(S!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(N.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(ud(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function Ds(e,t,i={}){let n=Jt(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=U.resolve(e.projectRoot),a=Mv(i),o=Fv(i.gitSelectionLimits),s=await Bv(a,r,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(zv(s).filter(g=>pa(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>pa(e,g)),d=(g,E)=>E.some(O=>g===O||g.startsWith(`${O}/`)),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 tC(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!p(g.path)&&pa(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Vv(a,r,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let g of l)N.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,E)=>g.path.localeCompare(E.path,"en"));let b=n.omitted.filter(g=>f(g.path)||p(g.path)||!pa(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(E=>E.startsWith(`${g.path}/`)):!0);for(let g of N)b.some(E=>E.path===g.path&&E.reason===g.reason)||b.push(g);b.sort((g,E)=>g.path.localeCompare(E.path,"en"));let S=n.omissionOverflow?.count??0,k=n.omissionOverflow?.hash??D("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,k=ma(k,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{S+=1,k=ma(k,"omission",g)};for(;b.length>od;){let g=Os(b);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+S===0,entries:v,omitted:b,omittedCount:b.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),w=y();for(;ud(w)>n.limits.maxManifestBytes;){let g=Os(b);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),w=y()}return Jt(w)}function Kv(e,t){if(!IP.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=U.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return U.join(i,"runtime","baseline-manifest.json")}async function Ms(e,t={}){let i={maxFiles:t.limits?.maxFiles??Ts.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Ts.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Ts.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Ts.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Wv(t.policy),r=Mv({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Fv(t.gitSelectionLimits),o=ZP(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=U.resolve(e.projectRoot),c=await ne.realpath(s),l=U.resolve(e.nativeRoot),u=await ne.realpath(l),d=U.resolve(e.configFile),f=U.join(s,".comet","current-change.json"),p=uC(s,t.denylist??[]),m=[],h=[],v=new Map,N=new Map,b=0,S=0,k=D("comet.native.snapshot-omission-overflow.v1"),R=0,y=!1,w=null,g=C=>{S+=1,k=ma(k,"omission",C)},E=C=>{if(b+=1,h.length<od){h.push(C);return}if(ad(C)){let A=Os(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),h.push(C);return}g(C)},O=C=>{b+=C.count,S+=C.count,k=ma(k,"git-selection",{source:"git-selection",...C})},Z=C=>{S+=1,k=ma(k,"manifest-entry",{reason:"manifest-size",entry:C})},z=async(C,A)=>{m.push(C),R+=C.size,v.set(C.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(C.path))},Y=(C,A)=>{let _=m.findIndex(oe=>oe.path===C);if(_<0)return;let[F]=m.splice(_,1);R-=F.size,v.delete(C),E(A)},ie=async(C,A,_,F)=>{if(!_.isFile()||_.isSymbolicLink()||!$(r))return;let oe;try{oe=await ne.realpath(C)}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;E({path:A,size:_.size,type:"file",reason:ue(j)?"changed-during-read":"unreadable"});return}if(!$(r)||!B(c,oe)||xi(u,oe))return;if(m.length>=i.maxFiles){E({path:A,size:_.size,type:"file",reason:"file-count"});return}if(_.size>i.maxFileBytes){E({path:A,size:_.size,type:"file",reason:"file-size"});return}if(R+_.size>i.maxTotalBytes){E({path:A,size:_.size,type:"file",reason:"total-size"});return}let J,H,x;try{if(J=await pC(oe,_.size,_,r),J.status==="budget-exhausted"||!$(r))return;if(J.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!$(r)||(x=await ne.realpath(C),!$(r)))return;H=await ne.lstat(C)}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;E({path:A,size:_.size,type:"file",reason:ue(j)?"changed-during-read":"unreadable"});return}if($(r)){if(J.bytes!==_.size||x!==oe||!Ci(_,J.finalStat)||!Ci(J.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==_.size||H.mtimeMs!==_.mtimeMs||H.ctimeMs!==_.ctimeMs){E({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}$(r)&&await z({path:A,hash:J.hash,size:H.size,type:"file",...F===void 0?{}:{gitObjectId:F}},{kind:"file",target:C,realTarget:oe,stat:H})}},Pt=async(C,A,_)=>{if(!$(r))return;let F,oe,J;try{if(F=await ne.readlink(C,{encoding:"buffer"}),!$(r)||(J=await ne.lstat(C),!$(r)))return;oe=await ne.readlink(C,{encoding:"buffer"})}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;E({path:A,size:null,type:"other",reason:ue(j)?"changed-during-read":"unreadable"});return}if(!$(r))return;if(!J.isSymbolicLink()||!Ci(_,J)||J.mtimeMs!==_.mtimeMs||J.ctimeMs!==_.ctimeMs||!F.equals(oe)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=F.byteLength;if(m.length>=i.maxFiles){E({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){E({path:A,size:H,type:"other",reason:"file-size"});return}if(R+H>i.maxTotalBytes){E({path:A,size:H,type:"other",reason:"total-size"});return}let x=$s("sha256").update("symlink\0").update(F).digest("hex");$(r)&&await z({path:A,hash:x,size:H,type:"file"},{kind:"symlink",target:C,rawTarget:F,stat:J})},Ct=async()=>{for(let[C,A]of[...v]){if(!$(r))return;if(A.kind==="file"){let H,x;try{if(H=await ne.realpath(A.target),!$(r))return;x=await ne.lstat(A.target)}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;Y(C,{path:C,size:null,type:"file",reason:de(j)?"unreadable":"changed-during-read"});continue}if(!$(r))return;(H!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!Ci(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&Y(C,{path:C,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,x;try{if(H=await ne.lstat(A.target),!$(r))return;x=await ne.readlink(A.target,{encoding:"buffer"})}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;Y(C,{path:C,size:null,type:"other",reason:de(j)?"unreadable":"changed-during-read"});continue}if(!$(r))return;(!H.isSymbolicLink()||!Ci(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&Y(C,{path:C,size:null,type:"other",reason:"changed-during-read"});continue}let _,F;try{if(_=await ne.realpath(A.target),!$(r))return;F=await ne.lstat(A.target)}catch{if(!$(r))return;Y(C,{path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(r))return;if(!(_===A.realTarget&&F.isDirectory()&&!F.isSymbolicLink()&&Ci(A.stat,F)&&B(c,_)&&!xi(u,_))){Y(C,{path:C,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!$(r))return;J=await _v(r,_)}catch(H){if(va(H))throw H;Y(C,{path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(r))return;J.dirty?Y(C,{path:C,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Y(C,{path:C,size:null,type:"directory",reason:"gitlink-changed"})}for(let[C,A]of N){if(!$(r))return;try{let _=await ne.lstat(A);if(!$(r))return;E({path:C,size:_.isFile()?_.size:null,type:_.isFile()?"file":_.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(_){if(!$(r))return;if(ue(_))continue;if(!de(_))throw _;E({path:C,size:null,type:"file",reason:"unreadable"})}}},Je=await Bv(r,s,a,t.gitSelectionHooks);if(Je===null){let C=await xv({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let F of C.records){if(F.type!=="file"&&F.type!=="symlink"||v.has(F.path))continue;if(Nt(r)<1)break;if(!jv(n,F.path,r))continue;if(Nt(r)<1)break;let oe=U.resolve(s,...F.path.split("/")),J;try{J=await ne.lstat(oe)}catch(H){if(!$(r))break;if(!de(H)&&!ue(H))throw H;E({path:F.path,size:null,type:"file",reason:ue(H)?"changed-during-read":"unreadable"});continue}if(Nt(r)<1)break;if(F.type==="symlink"&&J.isSymbolicLink()){if(await Pt(oe,F.path,J),Nt(r)<1)break;continue}if(F.type!=="file"||!J.isFile()||J.isSymbolicLink()){E({path:F.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ie(oe,F.path,J),Nt(r)<1)break}Nt(r)>=1&&await Ct();let A=await xv({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),_=cC(C.evidence,A.evidence);w=_.evidence;for(let F of[...C.omissions,...A.omissions,..._.omissions])h.some(oe=>oe.path===F.path&&oe.reason===F.reason)||E(F)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let C=t.incrementalBaseline,A=new Map,_=!1;if(C){let x=Jt(C);for(let j of x.entries)j.gitObjectId!==void 0&&A.set(j.path,j);_=A.size>0}let F=new Set,oe=!0;try{let x=await Is(r,s,["ls-files","--modified","-z"],nd);for(let j of x.toString("utf8").split("\0")){let ve=js(j);ve!==null&&F.add(ve)}}catch{_=!1,oe=!1,A.clear()}let J=new Set,H=new Set;for(let x of zv(Je)){if(v.has(x)||!pa(e,x))continue;if(Nt(r)<1)break;if(!jv(n,x,r))continue;if(Nt(r)<1)break;let j=U.resolve(s,...x.split("/"));if(j===d||j===f||p.some(We=>xi(We,j)))continue;if(Je.gitlinks.has(x)){if(m.length>=i.maxFiles){E({path:x,size:0,type:"file",reason:"file-count"});continue}let We,Qa;try{[We,Qa]=await Promise.all([ne.realpath(j),ne.lstat(j)])}catch{E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Qa.isSymbolicLink()||!Qa.isDirectory()||!B(c,We)||xi(u,We)){E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Sn=await _v(r,We);if(Sn.dirty){E({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await z({path:x,hash:Sn.hash,size:0,type:"file"},{kind:"gitlink",target:j,realTarget:We,stat:Qa,hash:Sn.hash})}catch(Sn){if(va(Sn))throw Sn;E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ve;try{ve=await ne.lstat(j)}catch(We){if(ue(We)&&Je.tracked.has(x)){N.set(x,j);continue}if(!de(We)&&!ue(We))throw We;E({path:x,size:null,type:"file",reason:ue(We)?"changed-during-read":"unreadable"});continue}if(ve.isSymbolicLink()){await Pt(j,x,ve);continue}if(!ve.isFile()){Je.nestedRepositories.has(x)||E({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let ft=Je.trackedObjectIds.get(x),ze=ft?A.get(x):void 0;if(_&&ze?.gitObjectId!==void 0&&ze.gitObjectId===ft&&!F.has(x)){if(m.length>=i.maxFiles){E({path:x,size:ze.size,type:"file",reason:"file-count"});continue}if(ze.size>i.maxFileBytes){E({path:x,size:ze.size,type:"file",reason:"file-size"});continue}if(R+ze.size>i.maxTotalBytes){E({path:x,size:ze.size,type:"file",reason:"total-size"});continue}m.push({...ze}),R+=ze.size,J.add(x);continue}let Vf=oe&&!F.has(x)?ft:void 0;await ie(j,x,ve,Vf),Vf!==void 0&&H.add(x)}if(await Ct(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Vv(r,s,a,Je,t.gitSelectionHooks?.outputChunkBytes),J.size>0||_&&H.size>0){let x=await Is(r,s,["ls-files","--modified","-z"],nd),j=new Set;for(let ve of x.toString("utf8").split("\0")){let ft=js(ve);ft!==null&&j.add(ft)}for(let ve of J){if(!j.has(ve))continue;let ft=m.find(ze=>ze.path===ve);Y(ve,{path:ve,size:ft?.size??null,type:"file",reason:"changed-during-read"})}for(let ve of H){if(!j.has(ve))continue;let ft=m.find(ze=>ze.path===ve);ft&&delete ft.gitObjectId}}for(let x of Je.omissions)E(x);Je.overflow&&O(Je.overflow)}m.sort((C,A)=>C.path.localeCompare(A.path,"en")),h.sort((C,A)=>C.path.localeCompare(A.path,"en"));let TN=Je===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Je.evidence?{gitSelection:Je.evidence}:{}},Bf=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:TN,createdAt:(t.now??new Date).toISOString(),complete:b===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:b,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Bc=Bf();for(;ud(Bc)>i.maxManifestBytes;){if(h.filter(A=>!ad(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let _=0;_<A;_+=1){let F=Os(h);if(F===null)break;g(F)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let _ of m.splice(-A))b+=1,Z(_)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Bc=Bf()}return Bc}async function dd(e,t,i={}){let r=(await qe(e.projectRoot))?.native.snapshot??qu;return Ms(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 fd(e,t,i){let n=Kv(e,t);await I(e.nativeRoot,n),await pe(n,Jt(i))}async function Un(e,t){let i=Kv(e,t);await I(e.nativeRoot,i);try{let n=await Ss({root:e.nativeRoot,file:i,maxBytes:_P,label:"Native baseline snapshot manifest"});return Jt(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as $C}from"crypto";import Vs from"path";var Ge=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"});import{createHash as xC}from"node:crypto";import{constants as Ls,promises as je}from"node:fs";import Ye from"node:path";import{TextDecoder as TC}from"node:util";import RC from"path";var Gv=(e,t)=>{let i=e[t];return i==null?null:String(i)};function wa(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 ga(e,t){let i=wa(e,t);if(RC.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 PC(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 Yv(e){if(!e.run_id)return null;let t=wa(e,"run_id"),i=wa(e,"skill"),n=wa(e,"skill_version"),r=wa(e,"skill_hash"),a=ga(e,"pending_ref"),o=ga(e,"trajectory_ref"),s=ga(e,"context_ref"),c=ga(e,"artifacts_ref"),l=ga(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:Gv(e,"current_step"),iteration:u,pending:Gv(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:PC(e)}}var QH=256*1024;var CC=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function AC(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=Yv(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Fs(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=>!CC.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 AC(t)}var Ce={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 Na(e,t){let i=Ye.relative(e,t);return i===""||!Ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ye.sep}`)}function Qv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ya(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 _C(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ti(e,t,i){let n=Ge[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Ye.resolve(e),a=Ye.resolve(r,...n.split("/"));if(!Na(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Xv(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function hd(e,t){let i=Ye.resolve(e),n=Ye.resolve(t);if(!Na(i,n))throw new Error("Native Run path is outside its change");let r=[await Xv(i)],a=i;for(let o of Ye.relative(i,n).split(Ye.sep).filter(Boolean)){a=Ye.join(a,o);let s;try{s=await Xv(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Na(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function qs(e){for(let t of e){let i=await je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!_C(t,i)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function IC(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 rn(e,t,i,n,r){let a=await hd(e,Ye.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await je.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=Qv(o),c=await je.realpath(t);if(!Na(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Ls.O_RDONLY:Ls.O_RDONLY|Ls.O_NOFOLLOW|Ls.O_NONBLOCK,u;try{u=await je.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),je.lstat(t),je.realpath(t)]);if(await qs(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!ya(s,d)||!ya(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await IC(u,i,n);await r?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([u.stat(),je.lstat(t),je.realpath(t)]);if(await qs(a),!v.isFile()||v.isSymbolicLink()||N!==c||!ya(s,h)||!ya(s,v))throw new Error(`${n} changed while reading`);let b;try{b=new TC("utf-8",{fatal:!0}).decode(m)}catch(S){throw new Error(`${n} is not valid UTF-8`,{cause:S})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function jC(e,t,i){let n=await hd(e,Ye.dirname(t));if(!n)return{exists:!1};let r;try{r=await je.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 je.realpath(t);if(!Na(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await qs(n),{exists:!0,identity:Qv(r),realPath:a}}async function OC(e,t,i,n){let r=await hd(e,Ye.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await je.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()||!ya(i.identity,a)||await je.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await qs(r)}async function Bs(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await jC(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Le(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await OC(e.changeDir,e.file,i,e.label)}});let n=await rn(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 Zv(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function eg(e){return`${JSON.stringify(e,null,2)}
|
|
176
|
-
`}function _i(e){return Fs(e)}async function Ne(e,t){let i=Ti(e,"stateRef"),n=await rn(e,i,Ce.runStateBytes,"Native Run state",t);return n?Fs(Zv(n.text,"Native Run state")):null}async function an(e,t,i){let n=Fs(t);await Bs({changeDir:e,file:Ti(e,"stateRef"),content:eg(n),maxBytes:Ce.runStateBytes,label:"Native Run state",hooks:i})}async function Oe(e,t,i){let n=Ti(e,"trajectoryRef",t),r=await rn(e,n,Ce.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>Ce.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ce.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 tg(e,t,i){return(await rn(e,Ti(e,"trajectoryRef",t),Ce.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function ig(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=Ti(e,"trajectoryRef",t),o=await rn(e,a,Ce.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(
|
|
177
|
-
`;if(Buffer.byteLength(a,"utf8")>Ce.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ce.trajectoryEventBytes} bytes`);let o=await rn(e,r,Ce.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ce.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ce.trajectoryEvents} events`);await Bs({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Ce.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function Kn(e,t,i){let n=await rn(e,Ti(e,"checkpointRef",t),Ce.checkpointBytes,"Native Run checkpoint",i);return n?Zv(n.text,"Native Run checkpoint"):null}async function rg(e,t,i,n){await Bs({changeDir:e,file:Ti(e,"checkpointRef",t),content:eg(i),maxBytes:Ce.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var
|
|
178
|
-
`)])}catch(d){if(!
|
|
175
|
+
${Buffer.byteLength(n)}:${n}`)}function ad(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Os(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!ad(i))return e.splice(t,1),i}return null}function Ci(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function mC(e,t,i,n){if(!$(n))return{status:"budget-exhausted"};let r;try{r=await ne.open(e,"r")}catch(c){if(!$(n))return{status:"budget-exhausted"};throw c}if(!$(n))return await r.close(),{status:"budget-exhausted"};let a=$s("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!$(n))return{status:"budget-exhausted"};let c=await r.stat();if(!$(n))return{status:"budget-exhausted"};if(!c.isFile()||!Ci(i,c))return{status:"changed"};for(;;){if(!$(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(!$(n))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!$(n))return{status:"budget-exhausted"};let d=await r.stat();return $(n)?!d.isFile()||!Ci(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 nt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function rt(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function zn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function $t(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Uv(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=U.posix.normalize(e);if(i!==e||U.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function vC(e,t){let i=nt(e,`Native snapshot entry ${t}`);rt(i,VP,`Native snapshot entry ${t}`);let n=Uv(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Hs.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:$t(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!Dv.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function gC(e,t){let i=nt(e,`Native snapshot omission ${t}`);if(rt(i,JP,`Native snapshot omission ${t}`),!UP.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!KP.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Uv(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:$t(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function wC(e){let t=nt(e,"Native snapshot omission overflow");if(rt(t,zP,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hs.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:zn(t.count,"Native snapshot omission overflow count")}}function Jn(e,t){let i=nt(e,t);if(rt(i,LP,t),typeof i.hash!="string"||!Hs.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=$t(i.recordCount,`${t} recordCount`),r=$t(i.storedRecordCount,`${t} storedRecordCount`),a=$t(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 Ov(e){let t=nt(e,"Native Git selection evidence");if(rt(t,FP,"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=Jn(t.stageBefore,"Native Git selection stageBefore"),n=Jn(t.combined,"Native Git selection combined"),r=Jn(t.stageAfter,"Native Git selection stageAfter"),a=Jn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Jn(t.finalCombined,"Native Git selection finalCombined"),s=Jn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(d=>d.overflow),l=!Ai(i,r)||!Ai(r,a)||!Ai(n,o)||!Ai(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 $v(e,t){let i=nt(e,t);if(rt(i,BP,t),typeof i.hash!="string"||!Hs.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=$t(i.visitedNodeCount,`${t} visitedNodeCount`),r=$t(i.recordCount,`${t} recordCount`),a=$t(i.storedRecordCount,`${t} storedRecordCount`),o=$t(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 yC(e){let t=nt(e,"Native physical selection evidence");if(rt(t,qP,"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=$v(t.before,"Native physical selection before"),n=$v(t.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!Jv(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 Jt(e){let t=nt(e,"Native content snapshot manifest");if(rt(t,OP,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!WP.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let y=nt(t.capture,"Native content snapshot capture");if(rt(y,DP,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let w=y.gitSelection===void 0?void 0:Ov(y.gitSelection),g=y.physicalSelection===void 0?void 0:yC(y.physicalSelection),E=null;if(y.projection!==void 0){let O=nt(y.projection,"Native content snapshot projection");if(rt(O,MP,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...O.selection===void 0?{}:{selection:Ov(O.selection)}}}if(y.provider==="git"){if(g||E)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...w?{gitSelection:w}:{}}}else{if(w)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(g&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");i=E?{provider:"physical-tree",projection:E}:{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=nt(t.limits,"Native content snapshot limits");rt(n,$P,"Native content snapshot limits");let r={maxFiles:zn(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:zn(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:zn(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:zn(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:zn(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let y=nt(t.policy,"Native snapshot policy");if(rt(y,HP,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Wv({include:y.include,exclude:y.exclude,hash:y.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(vC),s=t.omitted.map(gC),c=$t(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:wC(t.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>r.maxFileBytes)||o.reduce((y,w)=>y+w.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>od||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(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.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(y=>y.reason==="physical-enumeration-limit"),N=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...v,...N])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||N.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=i?.physicalSelection,S=b?.status==="overflow"||b?.status==="overflow-and-changed",k=b?.status==="changed"||b?.status==="overflow-and-changed";if(S!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(k!==(N.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(ud(R)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return R}async function Ds(e,t,i={}){let n=Jt(t);if(n.capture?.provider==="git"||n.capture?.projection||n.capture?.physicalSelection)return n;let r=U.resolve(e.projectRoot),a=Mv(i),o=Fv(i.gitSelectionLimits),s=await Bv(a,r,o,i.gitSelectionHooks);if(s===null)return n;let c=new Set(zv(s).filter(g=>pa(e,g))),l=[...s.gitlinks].filter(g=>c.has(g)),u=[...s.nestedRepositories].filter(g=>pa(e,g)),d=(g,E)=>E.some(O=>g===O||g.startsWith(`${O}/`)),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 iC(a,r,m),v=n.entries.filter(g=>!f(g.path)&&!p(g.path)&&pa(e,g.path)&&(c.has(g.path)||!h.has(g.path)));await Vv(a,r,o,s,i.gitSelectionHooks?.outputChunkBytes);let N=[...s.omissions];for(let g of l)N.push({path:g,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((g,E)=>g.path.localeCompare(E.path,"en"));let b=n.omitted.filter(g=>f(g.path)||p(g.path)||!pa(e,g.path)?!1:h.has(g.path)?c.has(g.path)||[...c].some(E=>E.startsWith(`${g.path}/`)):!0);for(let g of N)b.some(E=>E.path===g.path&&E.reason===g.reason)||b.push(g);b.sort((g,E)=>g.path.localeCompare(E.path,"en"));let S=n.omissionOverflow?.count??0,k=n.omissionOverflow?.hash??D("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,k=ma(k,"git-selection",{source:"git-selection",...s.overflow}));let R=g=>{S+=1,k=ma(k,"omission",g)};for(;b.length>od;){let g=Os(b);if(g===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");R(g)}let y=()=>({...n,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:b.length+S===0,entries:v,omitted:b,omittedCount:b.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),w=y();for(;ud(w)>n.limits.maxManifestBytes;){let g=Os(b);if(g===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");R(g),w=y()}return Jt(w)}function Kv(e,t){if(!jP.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=U.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return U.join(i,"runtime","baseline-manifest.json")}async function Ms(e,t={}){let i={maxFiles:t.limits?.maxFiles??Ts.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Ts.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Ts.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Ts.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},n=Wv(t.policy),r=Mv({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=Fv(t.gitSelectionLimits),o=eC(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=U.resolve(e.projectRoot),c=await ne.realpath(s),l=U.resolve(e.nativeRoot),u=await ne.realpath(l),d=U.resolve(e.configFile),f=U.join(s,".comet","current-change.json"),p=dC(s,t.denylist??[]),m=[],h=[],v=new Map,N=new Map,b=0,S=0,k=D("comet.native.snapshot-omission-overflow.v1"),R=0,y=!1,w=null,g=C=>{S+=1,k=ma(k,"omission",C)},E=C=>{if(b+=1,h.length<od){h.push(C);return}if(ad(C)){let A=Os(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");g(A),h.push(C);return}g(C)},O=C=>{b+=C.count,S+=C.count,k=ma(k,"git-selection",{source:"git-selection",...C})},Z=C=>{S+=1,k=ma(k,"manifest-entry",{reason:"manifest-size",entry:C})},z=async(C,A)=>{m.push(C),R+=C.size,v.set(C.path,A),y||(y=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(C.path))},Y=(C,A)=>{let _=m.findIndex(oe=>oe.path===C);if(_<0)return;let[F]=m.splice(_,1);R-=F.size,v.delete(C),E(A)},ie=async(C,A,_,F)=>{if(!_.isFile()||_.isSymbolicLink()||!$(r))return;let oe;try{oe=await ne.realpath(C)}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;E({path:A,size:_.size,type:"file",reason:ue(j)?"changed-during-read":"unreadable"});return}if(!$(r)||!B(c,oe)||xi(u,oe))return;if(m.length>=i.maxFiles){E({path:A,size:_.size,type:"file",reason:"file-count"});return}if(_.size>i.maxFileBytes){E({path:A,size:_.size,type:"file",reason:"file-size"});return}if(R+_.size>i.maxTotalBytes){E({path:A,size:_.size,type:"file",reason:"total-size"});return}let J,H,x;try{if(J=await mC(oe,_.size,_,r),J.status==="budget-exhausted"||!$(r))return;if(J.status==="changed"){E({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!$(r)||(x=await ne.realpath(C),!$(r)))return;H=await ne.lstat(C)}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;E({path:A,size:_.size,type:"file",reason:ue(j)?"changed-during-read":"unreadable"});return}if($(r)){if(J.bytes!==_.size||x!==oe||!Ci(_,J.finalStat)||!Ci(J.finalStat,H)||!H.isFile()||H.isSymbolicLink()||H.size!==_.size||H.mtimeMs!==_.mtimeMs||H.ctimeMs!==_.ctimeMs){E({path:A,size:H.isFile()?H.size:null,type:H.isFile()?"file":"other",reason:"changed-during-read"});return}$(r)&&await z({path:A,hash:J.hash,size:H.size,type:"file",...F===void 0?{}:{gitObjectId:F}},{kind:"file",target:C,realTarget:oe,stat:H})}},Pt=async(C,A,_)=>{if(!$(r))return;let F,oe,J;try{if(F=await ne.readlink(C,{encoding:"buffer"}),!$(r)||(J=await ne.lstat(C),!$(r)))return;oe=await ne.readlink(C,{encoding:"buffer"})}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;E({path:A,size:null,type:"other",reason:ue(j)?"changed-during-read":"unreadable"});return}if(!$(r))return;if(!J.isSymbolicLink()||!Ci(_,J)||J.mtimeMs!==_.mtimeMs||J.ctimeMs!==_.ctimeMs||!F.equals(oe)){E({path:A,size:null,type:"other",reason:"changed-during-read"});return}let H=F.byteLength;if(m.length>=i.maxFiles){E({path:A,size:H,type:"other",reason:"file-count"});return}if(H>i.maxFileBytes){E({path:A,size:H,type:"other",reason:"file-size"});return}if(R+H>i.maxTotalBytes){E({path:A,size:H,type:"other",reason:"total-size"});return}let x=$s("sha256").update("symlink\0").update(F).digest("hex");$(r)&&await z({path:A,hash:x,size:H,type:"file"},{kind:"symlink",target:C,rawTarget:F,stat:J})},Ct=async()=>{for(let[C,A]of[...v]){if(!$(r))return;if(A.kind==="file"){let H,x;try{if(H=await ne.realpath(A.target),!$(r))return;x=await ne.lstat(A.target)}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;Y(C,{path:C,size:null,type:"file",reason:de(j)?"unreadable":"changed-during-read"});continue}if(!$(r))return;(H!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!Ci(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&Y(C,{path:C,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let H,x;try{if(H=await ne.lstat(A.target),!$(r))return;x=await ne.readlink(A.target,{encoding:"buffer"})}catch(j){if(!$(r))return;if(!de(j)&&!ue(j))throw j;Y(C,{path:C,size:null,type:"other",reason:de(j)?"unreadable":"changed-during-read"});continue}if(!$(r))return;(!H.isSymbolicLink()||!Ci(A.stat,H)||H.mtimeMs!==A.stat.mtimeMs||H.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&Y(C,{path:C,size:null,type:"other",reason:"changed-during-read"});continue}let _,F;try{if(_=await ne.realpath(A.target),!$(r))return;F=await ne.lstat(A.target)}catch{if(!$(r))return;Y(C,{path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(r))return;if(!(_===A.realTarget&&F.isDirectory()&&!F.isSymbolicLink()&&Ci(A.stat,F)&&B(c,_)&&!xi(u,_))){Y(C,{path:C,size:null,type:"directory",reason:"gitlink-changed"});continue}let J;try{if(!$(r))return;J=await _v(r,_)}catch(H){if(va(H))throw H;Y(C,{path:C,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!$(r))return;J.dirty?Y(C,{path:C,size:null,type:"directory",reason:"gitlink-dirty"}):J.hash!==A.hash&&Y(C,{path:C,size:null,type:"directory",reason:"gitlink-changed"})}for(let[C,A]of N){if(!$(r))return;try{let _=await ne.lstat(A);if(!$(r))return;E({path:C,size:_.isFile()?_.size:null,type:_.isFile()?"file":_.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(_){if(!$(r))return;if(ue(_))continue;if(!de(_))throw _;E({path:C,size:null,type:"file",reason:"unreadable"})}}},Je=await Bv(r,s,a,t.gitSelectionHooks);if(Je===null){let C=await xv({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let F of C.records){if(F.type!=="file"&&F.type!=="symlink"||v.has(F.path))continue;if(Nt(r)<1)break;if(!jv(n,F.path,r))continue;if(Nt(r)<1)break;let oe=U.resolve(s,...F.path.split("/")),J;try{J=await ne.lstat(oe)}catch(H){if(!$(r))break;if(!de(H)&&!ue(H))throw H;E({path:F.path,size:null,type:"file",reason:ue(H)?"changed-during-read":"unreadable"});continue}if(Nt(r)<1)break;if(F.type==="symlink"&&J.isSymbolicLink()){if(await Pt(oe,F.path,J),Nt(r)<1)break;continue}if(F.type!=="file"||!J.isFile()||J.isSymbolicLink()){E({path:F.path,size:J.isFile()?J.size:null,type:J.isDirectory()?"directory":J.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ie(oe,F.path,J),Nt(r)<1)break}Nt(r)>=1&&await Ct();let A=await xv({execution:r,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),_=lC(C.evidence,A.evidence);w=_.evidence;for(let F of[...C.omissions,...A.omissions,..._.omissions])h.some(oe=>oe.path===F.path&&oe.reason===F.reason)||E(F)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let C=t.incrementalBaseline,A=new Map,_=!1;if(C){let x=Jt(C);for(let j of x.entries)j.gitObjectId!==void 0&&A.set(j.path,j);_=A.size>0}let F=new Set,oe=!0;try{let x=await Is(r,s,["ls-files","--modified","-z"],nd);for(let j of x.toString("utf8").split("\0")){let ve=js(j);ve!==null&&F.add(ve)}}catch{_=!1,oe=!1,A.clear()}let J=new Set,H=new Set;for(let x of zv(Je)){if(v.has(x)||!pa(e,x))continue;if(Nt(r)<1)break;if(!jv(n,x,r))continue;if(Nt(r)<1)break;let j=U.resolve(s,...x.split("/"));if(j===d||j===f||p.some(We=>xi(We,j)))continue;if(Je.gitlinks.has(x)){if(m.length>=i.maxFiles){E({path:x,size:0,type:"file",reason:"file-count"});continue}let We,Qa;try{[We,Qa]=await Promise.all([ne.realpath(j),ne.lstat(j)])}catch{E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Qa.isSymbolicLink()||!Qa.isDirectory()||!B(c,We)||xi(u,We)){E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Sn=await _v(r,We);if(Sn.dirty){E({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await z({path:x,hash:Sn.hash,size:0,type:"file"},{kind:"gitlink",target:j,realTarget:We,stat:Qa,hash:Sn.hash})}catch(Sn){if(va(Sn))throw Sn;E({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ve;try{ve=await ne.lstat(j)}catch(We){if(ue(We)&&Je.tracked.has(x)){N.set(x,j);continue}if(!de(We)&&!ue(We))throw We;E({path:x,size:null,type:"file",reason:ue(We)?"changed-during-read":"unreadable"});continue}if(ve.isSymbolicLink()){await Pt(j,x,ve);continue}if(!ve.isFile()){Je.nestedRepositories.has(x)||E({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let ft=Je.trackedObjectIds.get(x),ze=ft?A.get(x):void 0;if(_&&ze?.gitObjectId!==void 0&&ze.gitObjectId===ft&&!F.has(x)){if(m.length>=i.maxFiles){E({path:x,size:ze.size,type:"file",reason:"file-count"});continue}if(ze.size>i.maxFileBytes){E({path:x,size:ze.size,type:"file",reason:"file-size"});continue}if(R+ze.size>i.maxTotalBytes){E({path:x,size:ze.size,type:"file",reason:"total-size"});continue}m.push({...ze}),R+=ze.size,J.add(x);continue}let Vf=oe&&!F.has(x)?ft:void 0;await ie(j,x,ve,Vf),Vf!==void 0&&H.add(x)}if(await Ct(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Vv(r,s,a,Je,t.gitSelectionHooks?.outputChunkBytes),J.size>0||_&&H.size>0){let x=await Is(r,s,["ls-files","--modified","-z"],nd),j=new Set;for(let ve of x.toString("utf8").split("\0")){let ft=js(ve);ft!==null&&j.add(ft)}for(let ve of J){if(!j.has(ve))continue;let ft=m.find(ze=>ze.path===ve);Y(ve,{path:ve,size:ft?.size??null,type:"file",reason:"changed-during-read"})}for(let ve of H){if(!j.has(ve))continue;let ft=m.find(ze=>ze.path===ve);ft&&delete ft.gitObjectId}}for(let x of Je.omissions)E(x);Je.overflow&&O(Je.overflow)}m.sort((C,A)=>C.path.localeCompare(A.path,"en")),h.sort((C,A)=>C.path.localeCompare(A.path,"en"));let TN=Je===null?{provider:"physical-tree",...w?{physicalSelection:w}:{}}:{provider:"git",...Je.evidence?{gitSelection:Je.evidence}:{}},Bf=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:TN,createdAt:(t.now??new Date).toISOString(),complete:b===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:b,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:S}}:{}}),Bc=Bf();for(;ud(Bc)>i.maxManifestBytes;){if(h.filter(A=>!ad(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let _=0;_<A;_+=1){let F=Os(h);if(F===null)break;g(F)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let _ of m.splice(-A))b+=1,Z(_)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Bc=Bf()}return Bc}async function dd(e,t,i={}){let r=(await qe(e.projectRoot))?.native.snapshot??qu;return Ms(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 fd(e,t,i){let n=Kv(e,t);await I(e.nativeRoot,n),await pe(n,Jt(i))}async function Un(e,t){let i=Kv(e,t);await I(e.nativeRoot,i);try{let n=await Ss({root:e.nativeRoot,file:i,maxBytes:IP,label:"Native baseline snapshot manifest"});return Jt(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as HC}from"crypto";import Vs from"path";var Ge=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"});import{createHash as TC}from"node:crypto";import{constants as Ls,promises as je}from"node:fs";import Ye from"node:path";import{TextDecoder as _C}from"node:util";import PC from"path";var Gv=(e,t)=>{let i=e[t];return i==null?null:String(i)};function wa(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 ga(e,t){let i=wa(e,t);if(PC.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 CC(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 Yv(e){if(!e.run_id)return null;let t=wa(e,"run_id"),i=wa(e,"skill"),n=wa(e,"skill_version"),r=wa(e,"skill_hash"),a=ga(e,"pending_ref"),o=ga(e,"trajectory_ref"),s=ga(e,"context_ref"),c=ga(e,"artifacts_ref"),l=ga(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:Gv(e,"current_step"),iteration:u,pending:Gv(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:CC(e)}}var ZH=256*1024;var AC=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function xC(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=Yv(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Fs(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=>!AC.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 xC(t)}var Ce={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 Na(e,t){let i=Ye.relative(e,t);return i===""||!Ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ye.sep}`)}function Qv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ya(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 IC(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ti(e,t,i){let n=Ge[t];if(i!==void 0&&i!==n)throw new Error(`Native Run ${t} ref must be ${n}`);let r=Ye.resolve(e),a=Ye.resolve(r,...n.split("/"));if(!Na(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Xv(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function hd(e,t){let i=Ye.resolve(e),n=Ye.resolve(t);if(!Na(i,n))throw new Error("Native Run path is outside its change");let r=[await Xv(i)],a=i;for(let o of Ye.relative(i,n).split(Ye.sep).filter(Boolean)){a=Ye.join(a,o);let s;try{s=await Xv(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Na(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function qs(e){for(let t of e){let i=await je.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!IC(t,i)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function jC(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 rn(e,t,i,n,r){let a=await hd(e,Ye.dirname(t));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await je.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=Qv(o),c=await je.realpath(t);if(!Na(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?Ls.O_RDONLY:Ls.O_RDONLY|Ls.O_NOFOLLOW|Ls.O_NONBLOCK,u;try{u=await je.open(t,l)}catch(d){throw new Error(`${n} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),je.lstat(t),je.realpath(t)]);if(await qs(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!ya(s,d)||!ya(s,f))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await jC(u,i,n);await r?.beforeFinalCheck?.();let[h,v,N]=await Promise.all([u.stat(),je.lstat(t),je.realpath(t)]);if(await qs(a),!v.isFile()||v.isSymbolicLink()||N!==c||!ya(s,h)||!ya(s,v))throw new Error(`${n} changed while reading`);let b;try{b=new _C("utf-8",{fatal:!0}).decode(m)}catch(S){throw new Error(`${n} is not valid UTF-8`,{cause:S})}return{text:b,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function OC(e,t,i){let n=await hd(e,Ye.dirname(t));if(!n)return{exists:!1};let r;try{r=await je.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 je.realpath(t);if(!Na(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await qs(n),{exists:!0,identity:Qv(r),realPath:a}}async function $C(e,t,i,n){let r=await hd(e,Ye.dirname(t));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await je.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()||!ya(i.identity,a)||await je.realpath(t)!==i.realPath)throw new Error(`${n} changed before commit`);await qs(r)}async function Bs(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await OC(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Le(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await $C(e.changeDir,e.file,i,e.label)}});let n=await rn(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 Zv(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function eg(e){return`${JSON.stringify(e,null,2)}
|
|
176
|
+
`}function _i(e){return Fs(e)}async function Ne(e,t){let i=Ti(e,"stateRef"),n=await rn(e,i,Ce.runStateBytes,"Native Run state",t);return n?Fs(Zv(n.text,"Native Run state")):null}async function an(e,t,i){let n=Fs(t);await Bs({changeDir:e,file:Ti(e,"stateRef"),content:eg(n),maxBytes:Ce.runStateBytes,label:"Native Run state",hooks:i})}async function Oe(e,t,i){let n=Ti(e,"trajectoryRef",t),r=await rn(e,n,Ce.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>Ce.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ce.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 tg(e,t,i){return(await rn(e,Ti(e,"trajectoryRef",t),Ce.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function ig(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=Ti(e,"trajectoryRef",t),o=await rn(e,a,Ce.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(TC("sha256").update(o.text,"utf8").digest("hex")!==n)throw new Error("Native Run trajectory changed before repair");await Bs({changeDir:e,file:a,content:i,maxBytes:Ce.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:r})}async function ng(e,t,i,n){let r=Ti(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
177
|
+
`;if(Buffer.byteLength(a,"utf8")>Ce.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ce.trajectoryEventBytes} bytes`);let o=await rn(e,r,Ce.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ce.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ce.trajectoryEvents} events`);await Bs({changeDir:e,file:r,content:`${o?.text??""}${a}`,maxBytes:Ce.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function Kn(e,t,i){let n=await rn(e,Ti(e,"checkpointRef",t),Ce.checkpointBytes,"Native Run checkpoint",i);return n?Zv(n.text,"Native Run checkpoint"):null}async function rg(e,t,i,n){await Bs({changeDir:e,file:Ti(e,"checkpointRef",t),content:eg(i),maxBytes:Ce.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var DC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Js=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 pd(e){return HC("sha256").update(e).digest("hex")}function MC(e,t){if(!DC.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Vs.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return Vs.join(i,"runtime","trajectory.jsonl")}function FC(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 LC(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 qC(e,t){let i=t.lastIndexOf(10),n=t.subarray(0,i+1),r=FC(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(!LC(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:pd(t),targetHash:pd(l),tailHash:pd(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function ag(e,t){let i=MC(e,t);await I(e.nativeRoot,i);let n=Vs.join(e.changesDir,t),r=await tg(n,Ge.trajectoryRef);return r===null?{status:"clean",file:i}:qC(i,Buffer.from(r))}async function Gn(e,t){let i=await ag(e,t);return"inspection"in i?i.inspection:i}async function zs(e,t){let i=await Gn(e,t);if(i.status!=="clean")throw new Js(i)}async function og(e,t,i){return Ie(e,`repair trajectory tail for ${t}`,async()=>{let n=await ag(e,t);if(!("inspection"in n)){if(n.status==="clean")return null;throw new Js(n)}try{await ig(Vs.join(e.changesDir,t),Ge.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 Gn(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 BC}from"node:crypto";import{promises as Ws}from"node:fs";import Ii from"node:path";var ba=/^[a-f0-9]{64}$/u,VC=16*1024,JC=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function Yn(e){return JC.has(e)}function lg(e,t){let i=Ii.relative(e,t);return Ii.isAbsolute(i)||i===".."||i.startsWith(`..${Ii.sep}`)?null:i.replaceAll("\\","/")||"."}function zC(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function ug(e,t){if(e.length===0||zC(e)||e.includes("\\")||Ii.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=Ii.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function md(e,t){return BC("sha256").update(`${e}
|
|
179
179
|
${t}`).digest("hex")}async function sg(e,t){let i=await Ws.realpath(t),n=await Ws.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?Ii.normalize(i).toLowerCase():i;return md(e,`${r}
|
|
180
180
|
${n.dev}
|
|
181
181
|
${n.ino}
|
|
182
|
-
${n.birthtimeMs}`)}async function cg(e,t){let i=await Ws.realpath(t),n=await Ws.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?Ii.normalize(i).toLowerCase():i;return md(e,r)}function
|
|
182
|
+
${n.birthtimeMs}`)}async function cg(e,t){let i=await Ws.realpath(t),n=await Ws.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let r=process.platform==="win32"?Ii.normalize(i).toLowerCase():i;return md(e,r)}function WC(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 Us(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"||!ba.test(String(t.projectRootId))||!ba.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");WC(t.capturedAt),ug(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&&!ba.test(String(t.projectRootPathId))||a&&!ba.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ba.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid")}function Xn(e,t){return Ii.join(e.changesDir,t,"runtime","workspace.json")}function UC(e,t){let i=lg(e.nativeRoot,Xn(e,t));if(!i||i===".")throw new Error("Native workspace file escaped its root");return ug(i,"Native workspace file ref")}async function dg(e,t){try{let i=await _e({root:e.nativeRoot,ref:UC(e,t),maxBytes:VC});return JSON.parse(i.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vd(e,t){let i=await dg(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:(Us(i),i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function fg(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=lg(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([sg("comet.native.workspace-project-root.v2",e.paths.projectRoot),sg("comet.native.workspace-native-root.v2",e.paths.nativeRoot),cg("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),cg("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),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:md("comet.native.workspace-session.v2",`${i}
|
|
183
183
|
${n}
|
|
184
|
-
${e.sessionId}`)}:{}};return Us(s),s}async function Ks(e){let t=await fg(e),i=Xn(e.paths,e.name);return await I(e.paths.nativeRoot,i),await pe(i,t,{containedRoot:e.paths.nativeRoot}),t}async function Gs(e,t){let i=await dg(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Us(i),i)}async function hg(e){return await vd(e.paths,e.name)?Ks(e):null}async function pg(e){Us(e.identity);let t=await fg({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 me="comet.native.v3",ge="comet.native.v2",at="comet.native.v1",ji="comet.native.transition.v3",zt="comet.native.transition.v2",on="comet.native.transition.v1";var vg=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],
|
|
185
|
-
`);function Ra(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function yg(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 Xs(e){if(!wg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function eA(e){if(!wg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Ng(e,t){if(e.length===0||Wt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function tA(e,t){let i=Ra(e,`spec_changes[${t}]`);if(yg(i,GC,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(eA(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"&&Ng(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"||!wd.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"||!wd.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 iA(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 yd(e,t){if(yg(e,t,Se),typeof e.name!="string")throw new Error("Native change name is required");if(Xs(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"||!YC.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&&!XC.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(tA),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"||!QC.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"&&Ng(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!iA(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 Pa(e){let t=Ra(e,Se);if(t.schema!==at)throw new Error(`Expected ${at}`);return{schema:at,...yd(t,UC)}}function Ea(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gd(e,t,i){if(e===null)return null;let n=typeof e=="string"?ZC.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 nA(e){if(e==null)return null;if(typeof e!="string"||!wd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function rA(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 Oi(e){let t=Ra(e,Se);if(t.schema!==ge)throw new Error(`Expected ${ge}`);if(Ea(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ea(t.revision,"Native v2 revision"),...yd(t,gg)}}function ot(e){let t=Ra(e,Se);if(t.schema!==me){if(t.schema===at||t.schema===ge){let o=t.schema===at?Pa(t):Oi(t);throw new Sa(o.name,o.schema)}throw new cn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ea(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new cn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Ea(t.revision,"Native revision"),r=yd(t,KC),a=nA(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:me,minimum_runtime_version:3,revision:n,verification_protocol:rA(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:gd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:gd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:gd(t.partial_allowance,"Native partial_allowance","allowances")}}function aA(e){let t=Ra(e,Se);if(t.schema===at){let r=Pa(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${me}`}}if(t.schema===ge){let r=Oi(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${me}`}}if(t.schema!==me){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 cn(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Ea(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new cn(t.schema,i).message};let n=ot(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function sn(e){let t=ot(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 Qs(e){let t=Oi(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 T(e,t){Xs(t);let i=Wt.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Zn(e,t){let i=Wt.join(T(e,t),"runtime","schema-migration.json");await I(e.nativeRoot,i);try{return await mg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function er(e,t){let i=Wt.join(T(e,t),"runtime","checkpoint-journal.json");await I(e.nativeRoot,i);try{return await mg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var oA=256*1024;async function Nd(e,t=Wt.dirname(e)){let i=Wt.relative(t,e).split(Wt.sep).join("/"),n=await _e({root:t,ref:i,maxBytes:oA}),r=(0,Ys.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 st(e,t){let i=Wt.join(T(e,t),Se);await I(e.nativeRoot,i);let n=aA(await Nd(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Zn(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 sA(e,n.state),n)}async function sA(e,t){if(await Un(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Ae(e,t){let i=await st(e,t);if(i.status==="migration-required")throw new Sa(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new cn(i.schema,i.minimumRuntimeVersion);return i.state}async function bg(e,t,i){let n={...t,schema:me,minimum_runtime_version:3,revision:i+1},r=await Pv({expectedRevision:i,next:n,read:async()=>{let a=ot(await Nd(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Le(e,(0,Ys.stringify)(sn(a))),equals:(a,o)=>JSON.stringify(sn(a))===JSON.stringify(sn(o)),conflict:a=>new ka(t.name,i,a)});return Object.assign(t,r),r}async function Zs(e,t,i,n){if(await Mn(e.projectRoot),await Zn(e,t.name))throw new Sa(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await er(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Ae(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await zs(e,t.name);let a=Wt.join(T(e,t.name),Se);return await I(e.nativeRoot,a),bg(a,t,i)}async function Sg(e,t){return bg(e,t,t.revision)}async function kg(e){return ot(await Nd(e))}var Rg=["Outcome","Scope","Non-goals","Acceptance examples"],cA=[...Rg,"Constraints and invariants","Decisions","Open questions","Verification expectations"],lA=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Pg={maxFileBytes:Qr};function Cg(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
|
|
187
|
-
${Aa(t)}`).digest("hex")}var pA="comet.native.archive-preflight.v1",mA="comet.native.archive-preflight.v1",vA="comet.native.archive-operation.v1",gA=/^[a-f0-9]{64}$/u,Tg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function tc(e,t){return e<t?-1:e>t?1:0}function yA(e,t){if(typeof e!="string"||!gA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ut(e,t){return e===null?null:yA(e,t)}function NA(e,t){let i=xg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||xg.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 bA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function SA(e,t){if(!Tg.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=Ut(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=Ut(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=Ut(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 kA(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:Ut(e.contractHash,"Native archive contract hash"),acceptanceHash:Ut(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ut(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ut(e.reportHash,"Native archive report hash"),envelopeHash:Ut(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ut(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 EA(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!wA.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(tc);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function RA(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(tc)}function _g(e){if(!Tg.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(SA).sort((c,l)=>tc(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:M(vA,c)})),n=kA(e.evidence),r=[...new Set([...EA(e.findingCodes??[]),...RA({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(tc),a=bA(e.revision),o=NA(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:pA,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:M(mA,s)}}import{createHash as PA}from"node:crypto";import Ig from"node:path";var CA="comet.native.conflict-radar.v1",Be=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}),AA="comet.native.conflict-radar.v1",xA="comet.native.conflict-radar-signals.v1",TA=/^[a-f0-9]{64}$/u,$g=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_A=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),IA=new Set(["capability","operation","baseHash"]),jA=new Set(["path","kind"]);function tr(e,t){return e<t?-1:e>t?1:0}function Rd(e){return Buffer.byteLength(e,"utf8")}function Pd(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 Cd(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(Rd(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function OA(e,t){let i=Cd(e,t,Be.maxArtifactPathBytes),n=Ig.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)||Ig.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 Hg(e,t){if(typeof e!="string"||!TA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $A(e,t){let i=Pd(e,IA,t),n=Cd(i.capability,`${t} capability`,Be.maxCapabilityBytes);if(!$g.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:Hg(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 HA(e,t){let i=Pd(e,jA,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:OA(i.path,`${t} path`),kind:i.kind}}function DA(e,t){let i=Pd(e,_A,`Conflict radar change ${t}`),n=Cd(i.name,`Conflict radar change ${t} name`,Be.maxNameBytes);if(!$g.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>Be.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>Be.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>$A(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>tr(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)=>HA(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>tr(c.path,l.path)||tr(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:Hg(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function MA(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Be.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(DA).sort((r,a)=>tr(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)>Be.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Be.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function FA(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 LA(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 qA(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function BA(e,t){let i=[],n=PA("sha256").update(`${xA}
|
|
188
|
-
[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Aa(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Be.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(
|
|
184
|
+
${e.sessionId}`)}:{}};return Us(s),s}async function Ks(e){let t=await fg(e),i=Xn(e.paths,e.name);return await I(e.paths.nativeRoot,i),await pe(i,t,{containedRoot:e.paths.nativeRoot}),t}async function Gs(e,t){let i=await dg(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Us(i),i)}async function hg(e){return await vd(e.paths,e.name)?Ks(e):null}async function pg(e){Us(e.identity);let t=await fg({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 me="comet.native.v3",ge="comet.native.v2",at="comet.native.v1",ji="comet.native.transition.v3",zt="comet.native.transition.v2",on="comet.native.transition.v1";var vg=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],KC=new Set(vg),gg=new Set([...vg,"minimum_runtime_version","revision"]),GC=new Set([...gg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),YC=new Set(["capability","operation","source","base_hash"]),XC=new Set(["shape","build","verify","archive"]),QC=new Set(["implicit","confirmed"]),ZC=new Set(["pending","pass","fail"]),Se="comet-state.yaml",wd=/^[a-f0-9]{64}$/u,wg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eA=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Sa=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"},cn=class extends Error{constructor(i,n){super(i!==me||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"},ka=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"},Qn=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"},VD=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
185
|
+
`);function Ra(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function yg(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 Xs(e){if(!wg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function tA(e){if(!wg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Ng(e,t){if(e.length===0||Wt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function iA(e,t){let i=Ra(e,`spec_changes[${t}]`);if(yg(i,YC,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(tA(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"&&Ng(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"||!wd.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"||!wd.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 nA(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 yd(e,t){if(yg(e,t,Se),typeof e.name!="string")throw new Error("Native change name is required");if(Xs(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"||!XC.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&&!QC.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(iA),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"||!ZC.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"&&Ng(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!nA(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 Pa(e){let t=Ra(e,Se);if(t.schema!==at)throw new Error(`Expected ${at}`);return{schema:at,...yd(t,KC)}}function Ea(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gd(e,t,i){if(e===null)return null;let n=typeof e=="string"?eA.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 rA(e){if(e==null)return null;if(typeof e!="string"||!wd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function aA(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 Oi(e){let t=Ra(e,Se);if(t.schema!==ge)throw new Error(`Expected ${ge}`);if(Ea(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ge} minimum_runtime_version must be 2`);return{schema:ge,minimum_runtime_version:2,revision:Ea(t.revision,"Native v2 revision"),...yd(t,gg)}}function ot(e){let t=Ra(e,Se);if(t.schema!==me){if(t.schema===at||t.schema===ge){let o=t.schema===at?Pa(t):Oi(t);throw new Sa(o.name,o.schema)}throw new cn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=Ea(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new cn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=Ea(t.revision,"Native revision"),r=yd(t,GC),a=rA(t.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:me,minimum_runtime_version:3,revision:n,verification_protocol:aA(t.verification_protocol),...r,approved_contract_hash:a,implementation_scope:gd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:gd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:gd(t.partial_allowance,"Native partial_allowance","allowances")}}function oA(e){let t=Ra(e,Se);if(t.schema===at){let r=Pa(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${me}`}}if(t.schema===ge){let r=Oi(t);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${me}`}}if(t.schema!==me){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 cn(typeof t.schema=="string"?t.schema:"(missing)",r).message}}let i=Ea(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new cn(t.schema,i).message};let n=ot(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function sn(e){let t=ot(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 Qs(e){let t=Oi(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 T(e,t){Xs(t);let i=Wt.join(e.changesDir,t);if(!B(e.changesDir,i))throw new Error("Native change path escaped");return i}async function Zn(e,t){let i=Wt.join(T(e,t),"runtime","schema-migration.json");await I(e.nativeRoot,i);try{return await mg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function er(e,t){let i=Wt.join(T(e,t),"runtime","checkpoint-journal.json");await I(e.nativeRoot,i);try{return await mg.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var sA=256*1024;async function Nd(e,t=Wt.dirname(e)){let i=Wt.relative(t,e).split(Wt.sep).join("/"),n=await _e({root:t,ref:i,maxBytes:sA}),r=(0,Ys.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 st(e,t){let i=Wt.join(T(e,t),Se);await I(e.nativeRoot,i);let n=oA(await Nd(i,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Zn(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 cA(e,n.state),n)}async function cA(e,t){if(await Un(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Ae(e,t){let i=await st(e,t);if(i.status==="migration-required")throw new Sa(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new cn(i.schema,i.minimumRuntimeVersion);return i.state}async function bg(e,t,i){let n={...t,schema:me,minimum_runtime_version:3,revision:i+1},r=await Pv({expectedRevision:i,next:n,read:async()=>{let a=ot(await Nd(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Le(e,(0,Ys.stringify)(sn(a))),equals:(a,o)=>JSON.stringify(sn(a))===JSON.stringify(sn(o)),conflict:a=>new ka(t.name,i,a)});return Object.assign(t,r),r}async function Zs(e,t,i,n){if(await Mn(e.projectRoot),await Zn(e,t.name))throw new Sa(t.name,t.schema);if(!n?.allowPendingCheckpointRecovery&&await er(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Ae(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await zs(e,t.name);let a=Wt.join(T(e,t.name),Se);return await I(e.nativeRoot,a),bg(a,t,i)}async function Sg(e,t){return bg(e,t,t.revision)}async function kg(e){return ot(await Nd(e))}var Rg=["Outcome","Scope","Non-goals","Acceptance examples"],lA=[...Rg,"Constraints and invariants","Decisions","Open questions","Verification expectations"],uA=["Acceptance evidence","Commands and results","Skipped checks","Spec consistency","Known limitations and risks","Conclusion"],Pg={maxFileBytes:Qr};function Cg(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 dA(e,t){let i=Eg.resolve(e,...t.split(/[\\/]/u));if(!B(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let n=await bd.realpath(e),r=await bd.realpath(i);if(!B(n,r))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await bd.stat(r)).isFile())throw new Error(`Artifact is not a file: ${t}`);return r}function Ca(e){return{valid:e.length===0,findings:e}}async function Sd(e,t){let i=[],n;try{n=(await _e({root:e,ref:t,maxBytes:Pg.maxFileBytes})).text}catch(o){return Ca([{code:"brief-missing",message:o.message,path:t}])}let r=Cg(n);for(let o of lA)r.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of Rg)(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}),Ca(i)}async function kd(e,t){let i=[],n;try{n=(await _e({root:e,ref:t,maxBytes:Pg.maxFileBytes})).text}catch(a){return Ca([{code:"verification-missing",message:a.message,path:t}])}let r=Cg(n);for(let a of uA)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 Ca(i)}function ec(e,t){return Eg.join(e.specsDir,t,"spec.md")}async function Ag(e,t){let i=[],n=T(e,t.name);for(let r of t.spec_changes){let a=ec(e,r.capability),o=null;try{await I(e.nativeRoot,a),o=await yt(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 dA(n,r.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:r.source})}}return Ca(i)}import{promises as j_}from"node:fs";import gy from"node:path";import xg from"node:path";import{createHash as fA}from"crypto";function bt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function hA(e,t){t.has(e)&&bt("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)||bt("sparse arrays are not supported");return(i.length!==e.length||i.some((n,r)=>n!==String(r)))&&bt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&bt("symbol properties are not supported"),`[${e.map(n=>Ed(n,t)).join(",")}]`}finally{t.delete(e)}}function pA(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&bt("only plain objects are supported"),t.has(e)&&bt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&bt("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))&&bt("accessor properties are not supported"),`${JSON.stringify(o)}:${Ed(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Ed(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)||bt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?hA(e,t):pA(e,t);case"bigint":case"function":case"symbol":case"undefined":return bt(`${typeof e} values are not supported`)}return bt("unsupported value type")}function Aa(e){return Ed(e,new Set)}function M(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 fA("sha256").update(`${e}
|
|
187
|
+
${Aa(t)}`).digest("hex")}var mA="comet.native.archive-preflight.v1",vA="comet.native.archive-preflight.v1",gA="comet.native.archive-operation.v1",wA=/^[a-f0-9]{64}$/u,Tg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function tc(e,t){return e<t?-1:e>t?1:0}function NA(e,t){if(typeof e!="string"||!wA.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ut(e,t){return e===null?null:NA(e,t)}function bA(e,t){let i=xg.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||xg.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 SA(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function kA(e,t){if(!Tg.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=Ut(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),n=Ut(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),r=Ut(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 EA(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:Ut(e.contractHash,"Native archive contract hash"),acceptanceHash:Ut(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Ut(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Ut(e.reportHash,"Native archive report hash"),envelopeHash:Ut(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Ut(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 RA(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(n=>{if(typeof n!="string"||!yA.test(n))throw new Error(`Native archive preflight finding code is invalid: ${String(n)}`);return n}),i=[...new Set(t)].sort(tc);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function PA(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(tc)}function _g(e){if(!Tg.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(kA).sort((c,l)=>tc(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:M(gA,c)})),n=EA(e.evidence),r=[...new Set([...RA(e.findingCodes??[]),...PA({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:n})])].sort(tc),a=SA(e.revision),o=bA(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:mA,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:M(vA,s)}}import{createHash as CA}from"node:crypto";import Ig from"node:path";var AA="comet.native.conflict-radar.v1",Be=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}),xA="comet.native.conflict-radar.v1",TA="comet.native.conflict-radar-signals.v1",_A=/^[a-f0-9]{64}$/u,$g=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IA=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),jA=new Set(["capability","operation","baseHash"]),OA=new Set(["path","kind"]);function tr(e,t){return e<t?-1:e>t?1:0}function Rd(e){return Buffer.byteLength(e,"utf8")}function Pd(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 Cd(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(Rd(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function $A(e,t){let i=Cd(e,t,Be.maxArtifactPathBytes),n=Ig.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)||Ig.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 Hg(e,t){if(typeof e!="string"||!_A.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function HA(e,t){let i=Pd(e,jA,t),n=Cd(i.capability,`${t} capability`,Be.maxCapabilityBytes);if(!$g.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:Hg(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 DA(e,t){let i=Pd(e,OA,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:$A(i.path,`${t} path`),kind:i.kind}}function MA(e,t){let i=Pd(e,IA,`Conflict radar change ${t}`),n=Cd(i.name,`Conflict radar change ${t} name`,Be.maxNameBytes);if(!$g.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>Be.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>Be.maxArtifactsPerChange)throw new Error(`Conflict radar change ${n} exceeds the declared artifact budget`);let r=i.specs.map((c,l)=>HA(c,`Conflict radar change ${n} spec ${l}`)).sort((c,l)=>tr(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)=>DA(c,`Conflict radar change ${n} artifact ${l}`)).sort((c,l)=>tr(c.path,l.path)||tr(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:Hg(i.workspaceIdentityHash,`Conflict radar change ${n} workspace identity hash`);return{name:n,revision:i.revision,specs:r,declaredArtifacts:a,workspaceIdentityHash:s}}function FA(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Be.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(MA).sort((r,a)=>tr(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)>Be.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((r,a)=>r+a.declaredArtifacts.length,0)>Be.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function LA(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 qA(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 BA(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function VA(e,t){let i=[],n=CA("sha256").update(`${TA}
|
|
188
|
+
[`),r=0,a=!1,o=l=>{r>0&&n.update(","),n.update(Aa(l)),r+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<Be.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(LA(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=qA(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:BA(e,t),signalCount:r,signalHash:n.digest("hex"),signals:i,signalsTruncated:i.length!==r}}function jg(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function JA(e,t){return jg(e.classification)-jg(t.classification)||tr(e.left,t.left)||tr(e.right,t.right)}function Og(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:AA,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 Ad(e){let t=FA(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(VA(t[s],t[c]));i.sort(JA);let n=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),r=M(xA,{changes:t,relationships:n}),a=i.slice(0,Be.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Og(t,i,a,r);for(;a.length>0&&Rd(JSON.stringify(o))>Be.maxSerializedBytes;)a=a.slice(0,-1),o=Og(t,i,a,r);if(Rd(JSON.stringify(o))>Be.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as tT}from"node:crypto";import{promises as Et}from"node:fs";import Ht from"node:path";import{createHash as Vg}from"node:crypto";import Dg from"path";var xd="comet.native.implementation-scope.v2",Jg="comet.native.content-snapshot-projection.v1",xa="comet.native.content-snapshot-projection.v1",zg="comet.native.implementation-scope.v2",zA="comet.native.unresolved-scope-id.v1",WA="comet.native.scope-detail-overflow.v1",UA="comet.native.snapshot-projection-overflow.v2",jd=/^[a-f0-9]{64}$/u,un=1024*1024,KA=128,GA=128;function xe(e,t){return e<t?-1:e>t?1:0}function Td(e){if(!jd.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function YA(e,t){return e===t?0:e===null?-1:t===null?1:xe(e,t)}function Hi(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=Dg.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Dg.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Wg(e,t){return e==="."?e:Hi(e,t)}function ir(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function XA(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:Hi(e.path,`${t} path`),hash:e.hash,size:ir(e.size,`${t} size`),type:"file"}}function QA(e,t){return{path:Wg(e.path,`${t} path`),size:e.size===null?null:ir(e.size,`${t} size`),type:e.type,reason:e.reason}}function ZA(e,t){return xe(e.path,t.path)||xe(e.hash,t.hash)||e.size-t.size}function ex(e,t){return xe(e.path,t.path)||xe(e.reason,t.reason)||xe(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Ta(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
189
189
|
`,"utf8")}function $i(e,t,i){let n=`${t}
|
|
190
|
-
${Aa(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function
|
|
191
|
-
`),e.omissionOverflow&&$i(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,$i(a,"omission",f)},s=f=>{n+=1,r+=1,$i(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(;Ta(u)>un;){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 _d(e){let t=Jt(e),i=t.entries.map((r,a)=>
|
|
192
|
-
`);let i=0;Ug(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){$i(t,"change",r);let a=0;for(let o of e.declaredArtifacts)rc(o,r.path)&&(a+=1,$i(t,"change-attribution",o));$i(t,"change-end",{attributionCount:a}),a===0&&$i(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&&$i(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function Yg(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=ax(e,t,r,i.gitChangedPaths),s=M(xa,e),c=M(xa,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=KA)break;l.push(Kt({kind:"snapshot-omission",source:y,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${y} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Fg("baseline",e),...Fg("current",t),...o.totalChanges===0&&a===null?[Kt({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 y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},p=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),g=w.filter(Ct=>Ct.attributedTo.length===0),E=o.totalChanges-w.length,O=o.totalUnattributed-g.length,Z=u-y.detailedOmissionCount,z=O+Z,Y=[...g.map(Ct=>Kt({kind:"unattributed-change",source:"implementation-scope",path:Ct.path,evidence:{after:Ct.after,before:Ct.before,changeKind:Ct.kind}},`Changed path is not covered by a declared artifact: ${Ct.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||z>0?[Gg(y.overflowHash,{changes:E,unattributed:O,unresolved:z})]:[]],ie=nx(Y),Pt=y.includeGitAdvisory?f():void 0;return{schema:xd,contractHash:n,baselineProjectionRef:Td(s),baselineProjectionHash:s,currentProjectionRef:Td(c),currentProjectionHash:c,complete:ie.length===0,declaredArtifacts:r,changes:w,unattributed:g,unresolvedScopes:ie,noCodeReason:a,...Pt?{gitAdvisory:Pt}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N});if(Ta({...y,scopeHash:N})<=un)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 S=o.totalChanges>m||u>h?sx({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):N,k=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:S}),R={...k,scopeHash:M(zg,k)};if(Ta(R)>un)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function Od(e){let t=_d(e.baseline),i=_d(e.current),n=Kg(e);return{authority:n,baseline:t,current:i,scope:Yg(t,i,n)}}var cx=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Gt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yt(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 ln(e,t){if(typeof e!="string"||!jd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Lg(e,t,i){let n=Td(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function nr(e,t){let i=Gt(e,"Native snapshot projection");if(Yt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Jg)throw new Error("Native snapshot projection schema is invalid");let n=Jt({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=_d(n);if(M(xa,i)!==M(xa,r))throw new Error("Native snapshot projection is not canonical");let a=M(xa,r);if(t!==void 0&&ln(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function $d(e,t){let i=Gt(e,`Declared artifact ${t}`);if(Yt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Hi(i.path,`Declared artifact ${t} path`),kind:i.kind}}function qg(e,t){if(e===null)return null;let i=Gt(e,t);return Yt(i,["hash","size"],[],t),{hash:ln(i.hash,`${t} hash`),size:ir(i.size,`${t} size`)}}function Bg(e,t){let i=Gt(e,`Implementation change ${t}`);if(Yt(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($d),r=nc(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=qg(i.before,`Implementation change ${t} before`),o=qg(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:Hi(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function lx(e,t){let i=Gt(e,`Unresolved scope ${t}`);Yt(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"?Wg(i.path,`Unresolved scope ${t} path`):Hi(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function ic(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)=>Hi(r,`${t} ${a}`)),n=[...new Set(i)].sort(xe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function rr(e){let t=Gt(e,"Native implementation scope"),i=[...cx].filter(w=>w!=="gitAdvisory");if(Yt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==xd)throw new Error("Native implementation scope schema is invalid");let n=ln(t.contractHash,"Implementation scope contractHash"),r=ln(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Lg(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=ln(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Lg(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($d);if(JSON.stringify(c)!==JSON.stringify(nc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Bg),u=[...l].sort((w,g)=>xe(w.path,g.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(g=>rc(g,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Bg),p=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(lx),h=m.filter(w=>w.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:ox(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 N=t.noCodeReason,b=[...p.map(w=>Kt({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(v?.changes??0)===0&&N===null?[Kt({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")]:[]],S=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Id))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(S)!==JSON.stringify(b.sort(Id))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let k;if(t.gitAdvisory!==void 0){let w=Gt(t.gitAdvisory,"Implementation scope Git advisory");if(Yt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=ic(w.changedPaths,"Git changed paths"),E=ic(w.pathsPresentInSnapshotChanges,"Git present paths"),O=ic(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Z=[...E,...O].sort(xe),z=new Set(l.map(Y=>Y.path));if(JSON.stringify(Z)!==JSON.stringify(g)||(v?.changes??0)===0&&E.some(Y=>!z.has(Y))||O.some(Y=>z.has(Y)))throw new Error("Implementation scope Git advisory partition is invalid");k={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:O}}let R={schema:xd,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...k?{gitAdvisory:k}:{}},y=ln(t.scopeHash,"Implementation scope scopeHash");if(M(zg,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function ux(e){let t=Gt(e,"Native implementation scope authority");if(Yt(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($d);if(JSON.stringify(i)!==JSON.stringify(nc(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=ic(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Kg({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 _a(e){let t=Gt(e,"Native implementation scope bundle");Yt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=ux(t.authority),n=nr(t.baseline),r=nr(t.current),a=rr(t.scope),o=Yg(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 Xg(e){let t=rr(e.scope);return _a({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 Qg from"node:path";var dx=/\b(Bearer|Basic)\s+[^\s"']+/giu,fx=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,hx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,px=/\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,mx=/("(?:[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,vx=/(["'])((?:[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,gx=/\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 St(e){return e.replace(dx,"$1 [REDACTED]").replace(fx,"[REDACTED PRIVATE KEY]").replace(hx,"$1[REDACTED]@").replace(px,"[REDACTED TOKEN]").replace(mx,'$1"[REDACTED]"').replace(vx,"$1$2$1$3$4[REDACTED]$4").replace(gx,"$1$2[REDACTED]")}var ew=/^[a-f0-9]{64}$/u;var wx="comet.native.acceptance-trace.v2",yx="comet.native.partial-allowance.v1",Nx="comet.native.verification-evidence.v2";function Xt(e,t){if(!ew.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function iw(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 Hd(e,t,i=2e3){let n=St(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Ia(e,t){let i=Qg.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})||Qg.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 bx(e,t,i){let n=Ia(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Tt(n),a=n.toLowerCase(),o=i?Ia(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 Dd(e){let t=Ia(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 ar(e,t){return e<t?-1:e>t?1:0}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oc(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 nw(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 Zg(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 Sx(e){let t=ac(e,"Native acceptance trace");if(oc(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"||!ew.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=Ia(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=ac(o,`Native acceptance trace entry ${s}`);if(oc(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=>Dd(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar))||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:Ia(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Hd(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>ar(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=Xt(t.traceHash,"Native acceptance trace hash");if(M(wx,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function sc(e){let t=ac(e,"Native partial allowance");if(oc(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(ar))||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:iw(t.change),scopeHash:Xt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Hd(t.reason,"Partial allowance reason"),confirmedSummary:Hd(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:tw(t.sourceRevision),confirmedAt:nw(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=Xt(t.allowanceHash,"Native partial allowance hash");if(M(yx,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function ja(e){let t=ac(e,"Native verification evidence");if(oc(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=Xt(t.implementationScopeHash,"Native verification implementation scope hash"),n=Sx(t.acceptanceTrace),r=Xt(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:Xt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Dd(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ar)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(ar);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=>Dd(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar)))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:iw(t.change),sourceRevision:tw(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Xt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:Zg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:bx(t.reportRef,"Native verification report ref"),reportHash:Xt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:Zg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:nw(t.createdAt,"Native verification timestamp")},d=Xt(t.envelopeHash,"Native verification envelope hash");if(M(Nx,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import rw from"node:path";var aw="comet.native.check-receipt.v1",kx="comet.native.check-receipt.v1",or="scoped-text-safety",Md=1,ct=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Ex=/^[a-f0-9]{64}$/u,Rx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Px="comet.native.checker-policy.v1",Cx="comet.native.check-input.v1",Ax=2048,ow=M(Px,{policy:or,version:Md,limits:ct,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),xx=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),sw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],lw=["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"],Tx=new Set(lw);function fn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hn(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 Qt(e,t){if(typeof e!="string"||!Ex.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uw(e,t){let i=dn(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function cw(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 _x(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>Ax||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=rw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||rw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Ix(e){let t=fn(e,"Native check receipt checker");hn(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fn(t.limits,"Native check receipt limits");if(hn(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==or||t.version!==Md||t.hash!==ow||i.maxFiles!==ct.maxFiles||i.maxFileBytes!==ct.maxFileBytes||i.maxTotalBytes!==ct.maxTotalBytes||i.maxIssues!==ct.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:or,version:Md,hash:ow,limits:{...ct}}}function jx(e){let t=fn(e,"Native check receipt contract");return hn(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Qt(t.expectedHash,"Native check expected contract hash"),beforeHash:Qt(t.beforeHash,"Native check before contract hash"),afterHash:Qt(t.afterHash,"Native check after contract hash")}}function Ox(e){let t=fn(e,"Native check receipt implementation");return hn(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Qt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Qt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Qt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Qt(t.afterSnapshotHash,"Native check after snapshot hash")}}function $x(e){let t=fn(e,"Native check receipt counts");hn(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:dn(t.filesSelected,"Native check filesSelected"),filesScanned:dn(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:dn(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:dn(t.bytesScanned,"Native check bytesScanned"),issueCount:dn(t.issueCount,"Native check issueCount"),recordedIssueCount:dn(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>ct.maxFiles||i.bytesScanned>ct.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ct.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function Hx(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||sw.indexOf(e.kind)-sw.indexOf(t.kind)}function Dx(e){if(!Array.isArray(e)||e.length>ct.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=fn(n,`Native check issue ${r}`);if(hn(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!xx.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:_x(a.path,`Native check issue ${r} path`),line:uw(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(Hx);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function Mx(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!Tx.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=lw.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 Fx(e){return M(Cx,e)}function cc(e){let t=fn(e,"Native check receipt");if(hn(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==aw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!Rx.test(t.change))throw new Error("Native check receipt change name is invalid");let i=uw(t.sourceRevision,"Native check source revision"),n=Ix(t.checker),r=jx(t.contract),a=Ox(t.implementation),o=Fx({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Qt(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=cw(t.startedAt,"Native check receipt startedAt"),c=cw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=$x(t.counts),u=Dx(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=Mx(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>ct.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>ct.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:aw,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=Qt(t.receiptHash,"Native check receipt content hash");if(M(kx,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var Ld="comet.native.verification-receipt.v3",Lx=Ld,qx="comet.native.declared-artifacts.v1",Bx=/^[a-f0-9]{64}$/u,Vx=/^acceptance-[a-f0-9]{64}$/u,Jx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zx=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Wx=4096,Ux=256,Kx=1024;function sr(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 Di(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 Zt(e,t){if(typeof e!="string"||!Bx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=St(e).trim();if(!i||i.length>Wx||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Fd(e,t){let i=kt(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 Oa(e,t,i=kt,n=!1,r=Ux){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 Gx(e,t){if(typeof e!="string"||!Vx.test(e))throw new Error(`${t} is invalid`);return e}function Yx(e){let t=sr(e,"Native verification receipt bindings");if(Di(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Jx.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:Zt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Zt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Zt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Zt(t.artifactHash,"Native verification receipt artifact hash")}}function Xx(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=zx.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function Qx(e,t,i,n){let r=sr(t,`Native ${e} evidence`);if(e==="automated-check"){if(Di(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=Fd(r.startedAt,"Native automated-check start time"),o=Fd(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=sr(r.worktree,"Native automated-check worktree");if(Di(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=sr(r.afterFence,"Native automated-check after fence");if(Di(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:kt(r.executable,"Native automated-check executable"),args:Oa(r.args,"Native automated-check arguments",kt,!0),cwd:kt(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:kt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Zt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Zt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Zt(r.outputHash,"Native automated-check output hash"),outputSummary:kt(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Di(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=Xx(r.checkReceiptRef);if(Zt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Oa(r.subjects,"Native static inspection subjects",kt,n==="required-check"),rule:kt(r.rule,"Native static inspection rule"),resultSummary:kt(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Di(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Oa(r.steps,"Native manual evidence steps"),observations:Oa(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function Zx(e){let t=sr(e,"Native verification receipt");if(Di(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=kt(t.actor,"Native verification receipt actor"),o=Oa(t.acceptanceIds,"Native receipt acceptance IDs",Gx,n==="required-check",Kx).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:Ld,kind:i,role:n,status:r,bindings:Yx(t.bindings),acceptanceIds:o,actor:a,issuedAt:Fd(t.issuedAt,"Native verification receipt issue time"),evidence:Qx(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==or||s.actor!==`native-runtime:${or}`))throw new Error("Native required check policy identity is invalid");return s}function lc(e){let t=sr(e,"Native verification receipt");if(Di(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ld)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=Zx(n),a=Zt(t.receiptHash,"Native verification receipt hash");if(M(Lx,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function qd(e){return M(qx,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var pw=/^[a-f0-9]{64}$/u,Mi=un,$M=3*Mi;function Bd(e,t){let i=Ht.relative(e,t);return i===""||!Ht.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ht.sep}`)}function tT(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function uc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function dw(e){let t=await Et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function iT(e,t){let i=Ht.resolve(e),n=Ht.resolve(t);if(!Bd(i,n))throw new Error("Native evidence path is outside its change");let r=[await dw(i)],a=i;for(let o of Ht.relative(i,n).split(Ht.sep).filter(Boolean)){a=Ht.join(a,o);let s=await dw(a);if(!Bd(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function fw(e){for(let t of e){let i=await Et.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!tT(t,i)||await Et.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function nT(e,t,i={}){let n=await iT(t,Ht.dirname(e));await i.afterParentChainCaptured?.();let r=await Et.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Et.realpath(e);if(!Bd(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Et.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Et.lstat(e),Et.realpath(e)]);if(await fw(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!uc(s,r)||!uc(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Mi)throw new Error(`Native evidence document exceeds ${Mi} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Mi+1-d,N=await o.read(f,0,Math.min(f.length,v),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>Mi)throw new Error(`Native evidence document exceeds ${Mi} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Et.lstat(e),Et.realpath(e)]);if(await fw(n),!m.isFile()||m.isSymbolicLink()||h!==a||!uc(s,p)||!uc(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 lr(e,t){if(!pw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function mw(e){return lr("reports",e)}async function rT(e,t,i,n,r){if(!pw.test(i))throw new Error("Native report evidence hash is invalid");let a=await pn({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"||eT("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 cr(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 aT(e,t,i,n,r){return Ht.join(r??T(e,t),...lr(i,n).split("/"))}async function pn(e){let t=e.changeDir??T(e.paths,e.name),i=aT(e.paths,e.name,e.kind,e.hash,t);return await I(e.paths.nativeRoot,i),nT(i,t,e.hooks)}function hw(e,t){return nr(e,t)}function oT(e,t){let i=rr(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function sT(e,t,i){let n=sc(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function cT(e,t,i){let n=ja(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function lT(e,t,i,n=!1,r){let a=await Vd(e,t,i.implementationScopeRef,void 0,r);if(n&&await rT(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 vw(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 $a(e,t,i,n,r){let a=cr(i,"scopes"),o=oT(await pn({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=cr(o.baselineProjectionRef,"snapshots"),c=cr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([pn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>hw(d,s)),pn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>hw(d,c))]);return Xg({baseline:l,current:u,scope:o})}async function Vd(e,t,i,n,r){return(await $a(e,t,i,n,r)).scope}async function vw(e,t,i,n,r){let a=cr(i,"allowances");return sT(await pn({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function Jd(e,t,i,n,r){let a=cr(i,"receipts"),o=lc(await pn({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 Ha(e,t,i,n,r){let a=cr(i,"verifications"),o=cT(await pn({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await lT(e,t,o,!1,r),o}async function uT(e){try{let t=await Ue({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:Be.maxChanges});return await t.verify(),t.entries}catch(t){if(t.code==="ENOENT")return[];throw t}}async function dT(e,t){let i=await Ae(e,t),[n,r]=await Promise.all([i.implementation_scope?Vd(e,t,i.implementation_scope):null,Gs(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 fT(e){let i=(await uT(e)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();return Promise.all(i.map(n=>dT(e,n)))}async function dc(e,t){let i=await fT(e);Ad(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=Ad([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{promises as xT}from"fs";import TT from"path";import{isDeepStrictEqual as ef}from"util";var ur={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var hT=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function pT(e,t){return e<t?-1:e>t?1:0}function mT(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"||!hT.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(pT)}function zd(e=[]){return mT(e,"Native repair failed check IDs",ur.maxFailedCheckIds,!0)}function gw(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function vT(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:gw(e.failedAcceptanceIds,t.failedAcceptanceIds)&&gw(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Wd(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(vT(n,a))break;i+=1,n=a}return i}function Ud(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 ww="repairStagnation",Xe={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},wT=/^[a-f0-9]{64}$/u;var yT=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),NT=["data","runId","sequence","timestamp","type"],yw=["disposition","overrideSummaryHash","signatureHash"],bT=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Nw=12;function Gd(e,t){return e<t?-1:e>t?1:0}function bw(e,t,i){let n=Object.keys(e).sort(Gd);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function fc(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 Da(e,t){if(typeof e!="string"||!wT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ST(e){if(!Array.isArray(e)||e.length>ur.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(Gd)}function Sw(e){if(typeof e!="string"||e.length===0||e.length>Xe.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 Kd(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Xe.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xe.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>Xe.maxTextCharacters&&(!r||e.length>Xe.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Xe.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>Xe.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Kd(s,t+1,i,`${n}[${c}]`));return}let a=fc(e,n),o=Object.keys(a);if(o.length>Xe.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xe.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Xe.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Kd(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function kT(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 ET(e,t,i){let n=fc(e,`Native repair trajectory event ${t+1}`);if(bw(n,NT,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(kT(n.timestamp),typeof n.type!="string"||!yT.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(Sw(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 Kd(n.data,0,r,"Native trajectory event data"),fc(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Yd(e){let t=fc(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Gd),n=i.length===yw.length&&i.every((l,u)=>l===yw[u]);n||bw(t,bT,"Native repair trajectory projection");let r=Da(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Da(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Da(t.contractHash,"Native repair trajectory contract hash"),s=ST(t.failedAcceptanceIds),c=zd(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 RT(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 PT(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Nw;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Wd({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<ur.warningAtConsecutiveFailures?"continue":a<ur.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function CT(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Nw;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 kw(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xe.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Sw(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=ET(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xe.maxTotalDataNodes||c>Xe.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Da(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Da(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,ww)){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=Yd(f[ww]);if(RT(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),PT(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");CT(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>ur.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Ew(e){return kw(e).history}function Rw(e){let t=kw(e).latestProjection;return t?{...t}:null}var Dt={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:[]},Ma=D("comet-native-runtime:v3:semantic-repair-budget"),AT=[{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];function Pw(e){return e.skillVersion===Dt.definition.metadata.version&&e.skillHash===Ma||AT.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Xd={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 Fi(e){let i={sequence:(await Oe(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 ng(e.changeDir,e.run.trajectoryRef,i),i}async function mn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:D(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await rg(e.changeDir,e.run.checkpointRef,t),t}function Cw(e){return D(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 $w=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],_T=new Set($w),Hw=new Set([...$w,"minimum_runtime_version","revision"]),IT=new Set([...Hw,"operation"]),jT=512*1024,Qd=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),OT=new Set([...Qd,"implementationScopeHash","repairScopeHash","repairStagnation"]),Fa=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 Te(e,t){return TT.join(T(e,t),"runtime","transition.json")}function $T(e){return`transition-${e}`}async function HT(e,t,i){let n=$T(t);return yi(e,n,i)}async function vn(e,t,i,n){let r=await HT(e,t,i);try{return await n()}finally{await Ni(r)}}function pc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function tf(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 hc(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Mt(e,t){return ef(e,t)}function Zd(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=>!OT.has(u)),a=[...Qd].find(u=>!Object.hasOwn(i,u)),o=Qd.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(Ud(i.summary,"Native transition journal event summary"),St(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&&(Ud(i.noCodeReason,"Native transition journal event no-code reason"),St(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")?Yd(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 DT(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 Zd({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Zd(e,t)}function nf(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?DT(e.eventData,e.evidenceHash):Zd(e.eventData,e.evidenceHash),r=_i(e.nextRun),a=e.previousRun===null?null:_i(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function Aw(e,t,i=!1){if(e.skill!==Dt.definition.metadata.name||(i?!Pw(e):e.skillVersion!==Dt.definition.metadata.version||e.skillHash!==Ma)||e.orchestration!==Dt.definition.orchestration.mode||e.pendingRef!==Ge.pendingRef||e.trajectoryRef!==Ge.trajectoryRef||e.contextRef!==Ge.contextRef||e.artifactsRef!==Ge.artifactsRef||e.checkpointRef!==Ge.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function xw(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 Tw(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 rf(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Aw(a,"next Run",n||r!==null),Tw(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(Aw(r,"previous Run",!0),Tw(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(!ef(xw(r),xw(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function MT(e,t,i){return D(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Dw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function _w(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function af(e,t,i,n,r=!1){let a=i.eventData,o=_w(e),s=_w(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&&ef(e.spec_changes,t.spec_changes),l=Cw({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=MT(e.name,a.summary,t.spec_changes),l=D(`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 of(e,t){let i=pc(e);if(tf(i,IT),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);let n=hc(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 ${ji} minimum_runtime_version must be ${3}`);let r=hc(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=nf(i,t),o=ot(i.previousState),s=ot(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(af(o,s,a,i.operation),rf(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ji,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 FT(e,t){let i=pc(e);if(tf(i,_T),i.schema!==on)throw new Error(`Expected Native transition schema ${on}`);let n=nf(i,t,!0),r=Pa(i.previousState),a=Pa(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return af(r,a,n,Dw(r,a,n.eventData),!0),rf(r,a,n,!0),{schema:on,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 sf(e,t){let i=pc(e);if(tf(i,Hw),i.schema!==zt)throw new Error(`Expected Native transition schema ${zt}`);if(hc(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${zt} minimum_runtime_version must be 2`);let r=hc(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=nf(i,t,!0),o=Oi(i.previousState),s=Oi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(af(o,s,a,Dw(o,s,a.eventData),!0),rf(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:zt,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 LT(e,t){let i=pc(e);if(i.schema===ji)return{status:"current",journal:of(i,t)};if(i.schema===on)return{status:"migration-required",journal:FT(i,t)};if(i.schema===zt)return{status:"migration-required",journal:sf(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function cf(e,t){let i=Te(e,t);await I(e.nativeRoot,i);try{let n=await ee({root:e.nativeRoot,file:i,maxBytes:jT,label:`Native transition journal ${t}`});return LT(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ei(e,t){let i=await cf(e,t);if(!i)return null;if(i.status==="migration-required")throw new Fa(t);return i.journal}function Iw(e,t){if(Mt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Mt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function jw(e,t){if(Mt(e,t.nextState))return"next";if(Mt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function qT(e){let{journal:t}=e;return Mw({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 Mw(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Ow(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=qT({sequence:a.index+1,journal:t,type:a.event.type});if(!Mt(Mw(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 mc(e,t,i){if(await Zn(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await zs(e,t);let n=await ei(e,t);if(!n)return null;let r=T(e,t),a=Ow(await Oe(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([Ne(r),Ae(e,t)]),c=Iw(o,n),l=jw(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 an(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Mt(await Ne(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 Zs(e,n.nextState,n.previousState.revision);if(!Mt(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Mt(await Ae(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await ei(e,t);if(!u||!Mt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=Ow(await Oe(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Fi({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 Fi({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await mn({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([Ne(r),Ae(e,t)]);Iw(p,{...n,previousRun:n.nextRun}),jw(m,{...n,previousState:n.nextState});let h=await ei(e,t);if(!h||!Mt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await xT.rm(Te(e,t),{force:!0}),n.nextState}async function Fw(e,t,i){return Ie(e,`continue transition ${t}`,()=>vn(e,t,`continue transition ${t}`,()=>mc(e,t,i)))}import Lw from"node:path";var BT="comet.native.acceptance.v1",VT=/^acceptance-[a-f0-9]{64}$/u,JT=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),zT=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,WT=/^[a-f0-9]{64}$/u,UT=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function KT(e,t){return e<t?-1:e>t?1:0}var ti=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),La=Object.freeze({maxCriteria:1024}),qw="<!-- comet-native:acceptance-evidence:start -->",Bw="<!-- comet-native:acceptance-evidence:end -->";function Vw(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 Jw(e,t){let i=t.toString(36),n=M("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function GT(e){if(!WT.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=UT.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]!==M("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function YT(e,t){let i=Vw(e.text,ti.maxTextBytes),n=e.context.slice(0,ti.maxContextItems).map(r=>Vw(r,ti.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 Ww(e){let t=GT({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(KT),r=n.slice(0,ti.maxFailedCheckIds),a=e.criteria.slice(t,t+ti.maxItems);for(let c of a){let l=[...i,YT(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?Jw(e.acceptanceHash,u):null,limits:{...ti}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ti.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?Jw(e.acceptanceHash,o):null,limits:{...ti}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ti.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function df(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 lf(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 zw(e){return e.includes("-->")||e.includes("--!>")}function*dr(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
190
|
+
${Aa(i)}`;e.update(`${Buffer.byteLength(n,"utf8")}:`),e.update(n)}function tx(e){if(Ta(e)<=un)return e;let t=[...e.entries],i=[...e.omitted],n=e.omittedCount,r=e.omissionOverflow?.count??0,a=Vg("sha256");a.update(`${UA}
|
|
191
|
+
`),e.omissionOverflow&&$i(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(n+=1),r+=1,$i(a,"omission",f)},s=f=>{n+=1,r+=1,$i(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(;Ta(u)>un;){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 _d(e){let t=Jt(e),i=t.entries.map((r,a)=>XA(r,`Snapshot entry ${a}`));if(i.sort(ZA),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)=>QA(r,`Snapshot omission ${a}`));return n.sort(ex),tx({schema:Jg,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 nc(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:Hi(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)=>xe(i.path,n.path)||xe(i.kind,n.kind))}function rc(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Mg(e){return e?{hash:e.hash,size:e.size}:null}function Ug(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:xe(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:Mg(c),after:Mg(l)})}}function ix(e,t){return{...e,attributedTo:t.filter(i=>rc(i,e.path))}}function Kt(e,t){return{id:`scope:${M(zA,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function nx(e,t){let i=t.omitted.map(n=>Kt({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(Kt({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Kt({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 Fg(e,t){return nx(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function Id(e,t){return xe(e.kind,t.kind)||xe(e.source,t.source)||YA(e.path,t.path)||xe(e.id,t.id)}function rx(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(Id)}function ax(e){return[...new Set(e.map((t,i)=>Hi(t,`Git path ${i}`)))].sort(xe)}function Kg(e){if(typeof e.contractHash!="string"||!jd.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:nc(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:ax(e.gitChangedPaths)}}}function ox(e,t,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return Ug(e,t,d=>{let f=i.some(p=>rc(p,d.path));if(l+=1,f||(u+=1),a?.has(d.path)&&o.push(d.path),!c&&r.length<KA){let p=ix(d,i),m=Ta(p);s+m<=un?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function Gg(e,t){return Kt({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 sx(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:ir(Number(t[1]),"Scope overflow change count"),unresolved:ir(Number(t[2]),"Scope overflow unresolved count"),unattributed:ir(Number(t[3]),"Scope overflow unattributed count")},n=ln(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Gg(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function cx(e){let t=Vg("sha256");t.update(`${WA}
|
|
192
|
+
`);let i=0;Ug(e.baseline,e.current,r=>{if(i>=e.detailedChangeCount){$i(t,"change",r);let a=0;for(let o of e.declaredArtifacts)rc(o,r.path)&&(a+=1,$i(t,"change-attribution",o));$i(t,"change-end",{attributionCount:a}),a===0&&$i(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&&$i(t,"snapshot-omission",{source:r,...o}),n+=1;return t.digest("hex")}function Yg(e,t,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=ox(e,t,r,i.gitChangedPaths),s=M(xa,e),c=M(xa,t),l=[];for(let[y,w]of[["baseline",e],["current",t]])for(let g of w.omitted){if(l.length>=GA)break;l.push(Kt({kind:"snapshot-omission",source:y,path:g.path,evidence:{reason:g.reason,size:g.size,type:g.type}},`${y} snapshot omitted ${g.path}: ${g.reason}`))}let u=e.omitted.length+t.omitted.length,d=[...Fg("baseline",e),...Fg("current",t),...o.totalChanges===0&&a===null?[Kt({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 y=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(w=>y.has(w)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(w=>!y.has(w))}},p=y=>{let w=o.candidates.slice(0,y.detailedChangeCount),g=w.filter(Ct=>Ct.attributedTo.length===0),E=o.totalChanges-w.length,O=o.totalUnattributed-g.length,Z=u-y.detailedOmissionCount,z=O+Z,Y=[...g.map(Ct=>Kt({kind:"unattributed-change",source:"implementation-scope",path:Ct.path,evidence:{after:Ct.after,before:Ct.before,changeKind:Ct.kind}},`Changed path is not covered by a declared artifact: ${Ct.path}`)),...l.slice(0,y.detailedOmissionCount),...d,...E>0||z>0?[Gg(y.overflowHash,{changes:E,unattributed:O,unresolved:z})]:[]],ie=rx(Y),Pt=y.includeGitAdvisory?f():void 0;return{schema:xd,contractHash:n,baselineProjectionRef:Td(s),baselineProjectionHash:s,currentProjectionRef:Td(c),currentProjectionHash:c,complete:ie.length===0,declaredArtifacts:r,changes:w,unattributed:g,unresolvedScopes:ie,noCodeReason:a,...Pt?{gitAdvisory:Pt}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let y=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:N});if(Ta({...y,scopeHash:N})<=un)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 S=o.totalChanges>m||u>h?cx({baseline:e,current:t,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):N,k=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:S}),R={...k,scopeHash:M(zg,k)};if(Ta(R)>un)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return R}function Od(e){let t=_d(e.baseline),i=_d(e.current),n=Kg(e);return{authority:n,baseline:t,current:i,scope:Yg(t,i,n)}}var lx=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function Gt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yt(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 ln(e,t){if(typeof e!="string"||!jd.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Lg(e,t,i){let n=Td(t);if(e!==n)throw new Error(`${i} ref/hash mismatch`);return n}function nr(e,t){let i=Gt(e,"Native snapshot projection");if(Yt(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Jg)throw new Error("Native snapshot projection schema is invalid");let n=Jt({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=_d(n);if(M(xa,i)!==M(xa,r))throw new Error("Native snapshot projection is not canonical");let a=M(xa,r);if(t!==void 0&&ln(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function $d(e,t){let i=Gt(e,`Declared artifact ${t}`);if(Yt(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Hi(i.path,`Declared artifact ${t} path`),kind:i.kind}}function qg(e,t){if(e===null)return null;let i=Gt(e,t);return Yt(i,["hash","size"],[],t),{hash:ln(i.hash,`${t} hash`),size:ir(i.size,`${t} size`)}}function Bg(e,t){let i=Gt(e,`Implementation change ${t}`);if(Yt(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($d),r=nc(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=qg(i.before,`Implementation change ${t} before`),o=qg(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:Hi(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function ux(e,t){let i=Gt(e,`Unresolved scope ${t}`);Yt(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"?Wg(i.path,`Unresolved scope ${t} path`):Hi(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function ic(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)=>Hi(r,`${t} ${a}`)),n=[...new Set(i)].sort(xe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${t} must be sorted and unique`);return i}function rr(e){let t=Gt(e,"Native implementation scope"),i=[...lx].filter(w=>w!=="gitAdvisory");if(Yt(t,i,["gitAdvisory"],"Native implementation scope"),t.schema!==xd)throw new Error("Native implementation scope schema is invalid");let n=ln(t.contractHash,"Implementation scope contractHash"),r=ln(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Lg(t.baselineProjectionRef,r,"Implementation scope baseline projection"),o=ln(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Lg(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($d);if(JSON.stringify(c)!==JSON.stringify(nc(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Bg),u=[...l].sort((w,g)=>xe(w.path,g.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(g=>!d.has(`${g.kind}:${g.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(g=>rc(g,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Bg),p=l.filter(w=>w.attributedTo.length===0);if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(ux),h=m.filter(w=>w.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:sx(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 N=t.noCodeReason,b=[...p.map(w=>Kt({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(v?.changes??0)===0&&N===null?[Kt({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")]:[]],S=m.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(Id))||new Set(m.map(w=>w.id)).size!==m.length||JSON.stringify(S)!==JSON.stringify(b.sort(Id))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let k;if(t.gitAdvisory!==void 0){let w=Gt(t.gitAdvisory,"Implementation scope Git advisory");if(Yt(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let g=ic(w.changedPaths,"Git changed paths"),E=ic(w.pathsPresentInSnapshotChanges,"Git present paths"),O=ic(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Z=[...E,...O].sort(xe),z=new Set(l.map(Y=>Y.path));if(JSON.stringify(Z)!==JSON.stringify(g)||(v?.changes??0)===0&&E.some(Y=>!z.has(Y))||O.some(Y=>z.has(Y)))throw new Error("Implementation scope Git advisory partition is invalid");k={advisoryOnly:!0,changedPaths:g,pathsPresentInSnapshotChanges:E,pathsAbsentFromSnapshotChanges:O}}let R={schema:xd,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:N,...k?{gitAdvisory:k}:{}},y=ln(t.scopeHash,"Implementation scope scopeHash");if(M(zg,R)!==y)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:y}}function dx(e){let t=Gt(e,"Native implementation scope authority");if(Yt(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($d);if(JSON.stringify(i)!==JSON.stringify(nc(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=ic(t.gitChangedPaths,"Native implementation scope authority Git paths"));let r=Kg({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 _a(e){let t=Gt(e,"Native implementation scope bundle");Yt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=dx(t.authority),n=nr(t.baseline),r=nr(t.current),a=rr(t.scope),o=Yg(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 Xg(e){let t=rr(e.scope);return _a({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 Qg from"node:path";var fx=/\b(Bearer|Basic)\s+[^\s"']+/giu,hx=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,px=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,mx=/\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,vx=/("(?:[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,gx=/(["'])((?:[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,wx=/\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 St(e){return e.replace(fx,"$1 [REDACTED]").replace(hx,"[REDACTED PRIVATE KEY]").replace(px,"$1[REDACTED]@").replace(mx,"[REDACTED TOKEN]").replace(vx,'$1"[REDACTED]"').replace(gx,"$1$2$1$3$4[REDACTED]$4").replace(wx,"$1$2[REDACTED]")}var ew=/^[a-f0-9]{64}$/u;var yx="comet.native.acceptance-trace.v2",Nx="comet.native.partial-allowance.v1",bx="comet.native.verification-evidence.v2";function Xt(e,t){if(!ew.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function tw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function iw(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 Hd(e,t,i=2e3){let n=St(e).trim();if(n.length===0||n.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return n}function Ia(e,t){let i=Qg.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})||Qg.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 Sx(e,t,i){let n=Ia(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=Tt(n),a=n.toLowerCase(),o=i?Ia(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 Dd(e){let t=Ia(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 ar(e,t){return e<t?-1:e>t?1:0}function ac(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function oc(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 nw(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 Zg(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 kx(e){let t=ac(e,"Native acceptance trace");if(oc(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"||!ew.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=Ia(t.nativeRootRef,"Native root ref"),n=t.entries.map((o,s)=>{let c=ac(o,`Native acceptance trace entry ${s}`);if(oc(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=>Dd(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar))||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:Ia(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Hd(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>ar(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=Xt(t.traceHash,"Native acceptance trace hash");if(M(yx,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function sc(e){let t=ac(e,"Native partial allowance");if(oc(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(ar))||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:iw(t.change),scopeHash:Xt(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Hd(t.reason,"Partial allowance reason"),confirmedSummary:Hd(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:tw(t.sourceRevision),confirmedAt:nw(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=Xt(t.allowanceHash,"Native partial allowance hash");if(M(Nx,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function ja(e){let t=ac(e,"Native verification evidence");if(oc(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=Xt(t.implementationScopeHash,"Native verification implementation scope hash"),n=kx(t.acceptanceTrace),r=Xt(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:Xt(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Dd(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(ar)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(f=>f.evidenceRefs))].sort(ar);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=>Dd(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(ar)))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:iw(t.change),sourceRevision:tw(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Xt(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:Zg(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:Sx(t.reportRef,"Native verification report ref"),reportHash:Xt(t.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:Zg(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:nw(t.createdAt,"Native verification timestamp")},d=Xt(t.envelopeHash,"Native verification envelope hash");if(M(bx,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import rw from"node:path";var aw="comet.native.check-receipt.v1",Ex="comet.native.check-receipt.v1",or="scoped-text-safety",Md=1,ct=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),Rx=/^[a-f0-9]{64}$/u,Px=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Cx="comet.native.checker-policy.v1",Ax="comet.native.check-input.v1",xx=2048,ow=M(Cx,{policy:or,version:Md,limits:ct,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Tx=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),sw=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],lw=["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"],_x=new Set(lw);function fn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hn(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 Qt(e,t){if(typeof e!="string"||!Rx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function dn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function uw(e,t){let i=dn(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function cw(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 Ix(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>xx||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=rw.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||rw.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function jx(e){let t=fn(e,"Native check receipt checker");hn(t,["policy","version","hash","limits"],"Native check receipt checker");let i=fn(t.limits,"Native check receipt limits");if(hn(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==or||t.version!==Md||t.hash!==ow||i.maxFiles!==ct.maxFiles||i.maxFileBytes!==ct.maxFileBytes||i.maxTotalBytes!==ct.maxTotalBytes||i.maxIssues!==ct.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:or,version:Md,hash:ow,limits:{...ct}}}function Ox(e){let t=fn(e,"Native check receipt contract");return hn(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Qt(t.expectedHash,"Native check expected contract hash"),beforeHash:Qt(t.beforeHash,"Native check before contract hash"),afterHash:Qt(t.afterHash,"Native check after contract hash")}}function $x(e){let t=fn(e,"Native check receipt implementation");return hn(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Qt(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Qt(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Qt(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Qt(t.afterSnapshotHash,"Native check after snapshot hash")}}function Hx(e){let t=fn(e,"Native check receipt counts");hn(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts");let i={filesSelected:dn(t.filesSelected,"Native check filesSelected"),filesScanned:dn(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:dn(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:dn(t.bytesScanned,"Native check bytesScanned"),issueCount:dn(t.issueCount,"Native check issueCount"),recordedIssueCount:dn(t.recordedIssueCount,"Native check recordedIssueCount")};if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.filesScanned+i.binaryFilesSkipped>ct.maxFiles||i.bytesScanned>ct.maxTotalBytes||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ct.maxIssues)throw new Error("Native check receipt count accounting is invalid");return i}function Dx(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||sw.indexOf(e.kind)-sw.indexOf(t.kind)}function Mx(e){if(!Array.isArray(e)||e.length>ct.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((n,r)=>{let a=fn(n,`Native check issue ${r}`);if(hn(a,["path","line","kind"],`Native check issue ${r}`),typeof a.kind!="string"||!Tx.has(a.kind))throw new Error(`Native check issue ${r} kind is invalid`);return{path:Ix(a.path,`Native check issue ${r} path`),line:uw(a.line,`Native check issue ${r} line`),kind:a.kind}}),i=[...t].sort(Dx);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function Fx(e){if(!Array.isArray(e)||e.some(n=>typeof n!="string"||!_x.has(n)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=lw.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 Lx(e){return M(Ax,e)}function cc(e){let t=fn(e,"Native check receipt");if(hn(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==aw)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!Px.test(t.change))throw new Error("Native check receipt change name is invalid");let i=uw(t.sourceRevision,"Native check source revision"),n=jx(t.checker),r=Ox(t.contract),a=$x(t.implementation),o=Lx({change:t.change,sourceRevision:i,checkerHash:n.hash,contractHash:r.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Qt(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=cw(t.startedAt,"Native check receipt startedAt"),c=cw(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=Hx(t.counts),u=Mx(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=Fx(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>ct.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.filesSelected>ct.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:aw,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=Qt(t.receiptHash,"Native check receipt content hash");if(M(Ex,p)!==m)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:m}}var Ld="comet.native.verification-receipt.v3",qx=Ld,Bx="comet.native.declared-artifacts.v1",Vx=/^[a-f0-9]{64}$/u,Jx=/^acceptance-[a-f0-9]{64}$/u,zx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Wx=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ux=4096,Kx=256,Gx=1024;function sr(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 Di(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 Zt(e,t){if(typeof e!="string"||!Vx.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=St(e).trim();if(!i||i.length>Ux||i!==e.trim())throw new Error(`${t} is invalid`);return i}function Fd(e,t){let i=kt(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 Oa(e,t,i=kt,n=!1,r=Kx){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 Yx(e,t){if(typeof e!="string"||!Jx.test(e))throw new Error(`${t} is invalid`);return e}function Xx(e){let t=sr(e,"Native verification receipt bindings");if(Di(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!zx.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:Zt(t.contractHash,"Native verification receipt contract hash"),scopeHash:Zt(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Zt(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Zt(t.artifactHash,"Native verification receipt artifact hash")}}function Qx(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Wx.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function Zx(e,t,i,n){let r=sr(t,`Native ${e} evidence`);if(e==="automated-check"){if(Di(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=Fd(r.startedAt,"Native automated-check start time"),o=Fd(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=sr(r.worktree,"Native automated-check worktree");if(Di(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=sr(r.afterFence,"Native automated-check after fence");if(Di(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:kt(r.executable,"Native automated-check executable"),args:Oa(r.args,"Native automated-check arguments",kt,!0),cwd:kt(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:kt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Zt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Zt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Zt(r.outputHash,"Native automated-check output hash"),outputSummary:kt(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(e==="static-inspection"){Di(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=Qx(r.checkReceiptRef);if(Zt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Oa(r.subjects,"Native static inspection subjects",kt,n==="required-check"),rule:kt(r.rule,"Native static inspection rule"),resultSummary:kt(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Di(r,["steps","observations"],"Native manual-evidence evidence"),{steps:Oa(r.steps,"Native manual evidence steps"),observations:Oa(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function eT(e){let t=sr(e,"Native verification receipt");if(Di(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=kt(t.actor,"Native verification receipt actor"),o=Oa(t.acceptanceIds,"Native receipt acceptance IDs",Yx,n==="required-check",Gx).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:Ld,kind:i,role:n,status:r,bindings:Xx(t.bindings),acceptanceIds:o,actor:a,issuedAt:Fd(t.issuedAt,"Native verification receipt issue time"),evidence:Zx(i,t.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==or||s.actor!==`native-runtime:${or}`))throw new Error("Native required check policy identity is invalid");return s}function lc(e){let t=sr(e,"Native verification receipt");if(Di(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ld)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=t,r=eT(n),a=Zt(t.receiptHash,"Native verification receipt hash");if(M(qx,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function qd(e){return M(Bx,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var pw=/^[a-f0-9]{64}$/u,Mi=un,HM=3*Mi;function Bd(e,t){let i=Ht.relative(e,t);return i===""||!Ht.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ht.sep}`)}function iT(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function uc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function dw(e){let t=await Et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function nT(e,t){let i=Ht.resolve(e),n=Ht.resolve(t);if(!Bd(i,n))throw new Error("Native evidence path is outside its change");let r=[await dw(i)],a=i;for(let o of Ht.relative(i,n).split(Ht.sep).filter(Boolean)){a=Ht.join(a,o);let s=await dw(a);if(!Bd(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function fw(e){for(let t of e){let i=await Et.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!iT(t,i)||await Et.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function rT(e,t,i={}){let n=await nT(t,Ht.dirname(e));await i.afterParentChainCaptured?.();let r=await Et.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Et.realpath(e);if(!Bd(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Et.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Et.lstat(e),Et.realpath(e)]);if(await fw(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!uc(s,r)||!uc(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Mi)throw new Error(`Native evidence document exceeds ${Mi} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=Mi+1-d,N=await o.read(f,0,Math.min(f.length,v),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>Mi)throw new Error(`Native evidence document exceeds ${Mi} bytes`);u.push(Buffer.from(f.subarray(0,N.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Et.lstat(e),Et.realpath(e)]);if(await fw(n),!m.isFile()||m.isSymbolicLink()||h!==a||!uc(s,p)||!uc(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 lr(e,t){if(!pw.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function mw(e){return lr("reports",e)}async function aT(e,t,i,n,r){if(!pw.test(i))throw new Error("Native report evidence hash is invalid");let a=await pn({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"||tT("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 cr(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 oT(e,t,i,n,r){return Ht.join(r??T(e,t),...lr(i,n).split("/"))}async function pn(e){let t=e.changeDir??T(e.paths,e.name),i=oT(e.paths,e.name,e.kind,e.hash,t);return await I(e.paths.nativeRoot,i),rT(i,t,e.hooks)}function hw(e,t){return nr(e,t)}function sT(e,t){let i=rr(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function cT(e,t,i){let n=sc(e);if(n.change!==t||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function lT(e,t,i){let n=ja(e);if(n.change!==t||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function uT(e,t,i,n=!1,r){let a=await Vd(e,t,i.implementationScopeRef,void 0,r);if(n&&await aT(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 vw(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 $a(e,t,i,n,r){let a=cr(i,"scopes"),o=sT(await pn({paths:e,name:t,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=cr(o.baselineProjectionRef,"snapshots"),c=cr(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([pn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:r}).then(d=>hw(d,s)),pn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:r}).then(d=>hw(d,c))]);return Xg({baseline:l,current:u,scope:o})}async function Vd(e,t,i,n,r){return(await $a(e,t,i,n,r)).scope}async function vw(e,t,i,n,r){let a=cr(i,"allowances");return cT(await pn({paths:e,name:t,kind:"allowances",hash:a,hooks:n,changeDir:r}),t,a)}async function Jd(e,t,i,n,r){let a=cr(i,"receipts"),o=lc(await pn({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 Ha(e,t,i,n,r){let a=cr(i,"verifications"),o=lT(await pn({paths:e,name:t,kind:"verifications",hash:a,hooks:n,changeDir:r}),t,a);return await uT(e,t,o,!1,r),o}async function dT(e){try{let t=await Ue({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:Be.maxChanges});return await t.verify(),t.entries}catch(t){if(t.code==="ENOENT")return[];throw t}}async function fT(e,t){let i=await Ae(e,t),[n,r]=await Promise.all([i.implementation_scope?Vd(e,t,i.implementation_scope):null,Gs(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 hT(e){let i=(await dT(e)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();return Promise.all(i.map(n=>fT(e,n)))}async function dc(e,t){let i=await hT(e);Ad(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=Ad([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{promises as TT}from"fs";import _T from"path";import{isDeepStrictEqual as ef}from"util";var ur={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var pT=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function mT(e,t){return e<t?-1:e>t?1:0}function vT(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"||!pT.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(mT)}function zd(e=[]){return vT(e,"Native repair failed check IDs",ur.maxFailedCheckIds,!0)}function gw(e,t){let i=new Set(t);return e.every(n=>i.has(n))}function gT(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:gw(e.failedAcceptanceIds,t.failedAcceptanceIds)&&gw(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Wd(e,t){let i=1,n=e;for(let r=t.length-1;r>=0;r-=1){let a=t[r];if(gT(n,a))break;i+=1,n=a}return i}function Ud(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 ww="repairStagnation",Xe={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},yT=/^[a-f0-9]{64}$/u;var NT=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),bT=["data","runId","sequence","timestamp","type"],yw=["disposition","overrideSummaryHash","signatureHash"],ST=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],Nw=12;function Gd(e,t){return e<t?-1:e>t?1:0}function bw(e,t,i){let n=Object.keys(e).sort(Gd);if(n.length!==t.length||n.some((r,a)=>r!==t[a]))throw new Error(`${i} fields are invalid`)}function fc(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 Da(e,t){if(typeof e!="string"||!yT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kT(e){if(!Array.isArray(e)||e.length>ur.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(Gd)}function Sw(e){if(typeof e!="string"||e.length===0||e.length>Xe.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 Kd(e,t,i,n,r=!1){if(i.nodes+=1,i.nodes>Xe.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xe.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>Xe.maxTextCharacters&&(!r||e.length>Xe.maxEventDataCharacters))throw new Error(`${n} contains oversized text`);if(i.characters+=e.length,i.characters>Xe.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>Xe.maxArrayEntries)throw new Error(`${n} contains an oversized array`);e.forEach((s,c)=>Kd(s,t+1,i,`${n}[${c}]`));return}let a=fc(e,n),o=Object.keys(a);if(o.length>Xe.maxObjectFields)throw new Error(`${n} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xe.maxKeyCharacters)throw new Error(`${n} contains an invalid field name`);if(i.characters+=s.length,i.characters>Xe.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Kd(a[s],t+1,i,`${n}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function ET(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 RT(e,t,i){let n=fc(e,`Native repair trajectory event ${t+1}`);if(bw(n,bT,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(n.sequence)||n.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(ET(n.timestamp),typeof n.type!="string"||!NT.has(n.type))throw new Error("Native repair trajectory event type is invalid");if(Sw(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 Kd(n.data,0,r,"Native trajectory event data"),fc(n.data,"Native repair trajectory event data"),{event:n,dataNodes:r.nodes,dataCharacters:r.characters}}function Yd(e){let t=fc(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Gd),n=i.length===yw.length&&i.every((l,u)=>l===yw[u]);n||bw(t,ST,"Native repair trajectory projection");let r=Da(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Da(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Da(t.contractHash,"Native repair trajectory contract hash"),s=kT(t.failedAcceptanceIds),c=zd(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 PT(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 CT(e,t){let i=t.filter(s=>s.kind==="failure"),n=i.length+1,r=e.maxVerifyFailures??Nw;if(n>r)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Wd({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=n>=r?"hard-stop":a<ur.warningAtConsecutiveFailures?"continue":a<ur.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function AT(e,t,i){let n=t.filter(a=>a.kind==="failure"),r=i?.maxVerifyFailures??Nw;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 kw(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xe.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=Sw(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=RT(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xe.maxTotalDataNodes||c>Xe.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Da(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Da(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,ww)){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=Yd(f[ww]);if(PT(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),CT(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");AT(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>ur.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:n}}function Ew(e){return kw(e).history}function Rw(e){let t=kw(e).latestProjection;return t?{...t}:null}var Dt={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:[]},Ma=D("comet-native-runtime:v3:semantic-repair-budget"),xT=[{skillVersion:"2",skillHash:D("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:D("comet-native-runtime:v1")}];function Pw(e){return e.skillVersion===Dt.definition.metadata.version&&e.skillHash===Ma||xT.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Xd={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 Fi(e){let i={sequence:(await Oe(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 ng(e.changeDir,e.run.trajectoryRef,i),i}async function mn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:D(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await rg(e.changeDir,e.run.checkpointRef,t),t}function Cw(e){return D(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 $w=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],IT=new Set($w),Hw=new Set([...$w,"minimum_runtime_version","revision"]),jT=new Set([...Hw,"operation"]),OT=512*1024,Qd=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),$T=new Set([...Qd,"implementationScopeHash","repairScopeHash","repairStagnation"]),Fa=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 Te(e,t){return _T.join(T(e,t),"runtime","transition.json")}function HT(e){return`transition-${e}`}async function DT(e,t,i){let n=HT(t);return yi(e,n,i)}async function vn(e,t,i,n){let r=await DT(e,t,i);try{return await n()}finally{await Ni(r)}}function pc(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function tf(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 hc(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Mt(e,t){return ef(e,t)}function Zd(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=>!$T.has(u)),a=[...Qd].find(u=>!Object.hasOwn(i,u)),o=Qd.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(Ud(i.summary,"Native transition journal event summary"),St(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&&(Ud(i.noCodeReason,"Native transition journal event no-code reason"),St(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")?Yd(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 MT(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 Zd({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Zd(e,t)}function nf(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?MT(e.eventData,e.evidenceHash):Zd(e.eventData,e.evidenceHash),r=_i(e.nextRun),a=e.previousRun===null?null:_i(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:r,eventData:n}}function Aw(e,t,i=!1){if(e.skill!==Dt.definition.metadata.name||(i?!Pw(e):e.skillVersion!==Dt.definition.metadata.version||e.skillHash!==Ma)||e.orchestration!==Dt.definition.orchestration.mode||e.pendingRef!==Ge.pendingRef||e.trajectoryRef!==Ge.trajectoryRef||e.contextRef!==Ge.contextRef||e.artifactsRef!==Ge.artifactsRef||e.checkpointRef!==Ge.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function xw(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 Tw(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 rf(e,t,i,n=!1){let{previousRun:r,nextRun:a}=i;if(Aw(a,"next Run",n||r!==null),Tw(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(Aw(r,"previous Run",!0),Tw(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(!ef(xw(r),xw(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function FT(e,t,i){return D(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Dw(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function _w(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function af(e,t,i,n,r=!1){let a=i.eventData,o=_w(e),s=_w(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&&ef(e.spec_changes,t.spec_changes),l=Cw({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=FT(e.name,a.summary,t.spec_changes),l=D(`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 of(e,t){let i=pc(e);if(tf(i,jT),i.schema!==ji)throw new Error(`Expected Native transition schema ${ji}`);let n=hc(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 ${ji} minimum_runtime_version must be ${3}`);let r=hc(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=nf(i,t),o=ot(i.previousState),s=ot(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(af(o,s,a,i.operation),rf(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:ji,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 LT(e,t){let i=pc(e);if(tf(i,IT),i.schema!==on)throw new Error(`Expected Native transition schema ${on}`);let n=nf(i,t,!0),r=Pa(i.previousState),a=Pa(i.nextState);if(r.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return af(r,a,n,Dw(r,a,n.eventData),!0),rf(r,a,n,!0),{schema:on,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 sf(e,t){let i=pc(e);if(tf(i,Hw),i.schema!==zt)throw new Error(`Expected Native transition schema ${zt}`);if(hc(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${zt} minimum_runtime_version must be 2`);let r=hc(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=nf(i,t,!0),o=Oi(i.previousState),s=Oi(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(af(o,s,a,Dw(o,s,a.eventData),!0),rf(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:zt,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 qT(e,t){let i=pc(e);if(i.schema===ji)return{status:"current",journal:of(i,t)};if(i.schema===on)return{status:"migration-required",journal:LT(i,t)};if(i.schema===zt)return{status:"migration-required",journal:sf(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function cf(e,t){let i=Te(e,t);await I(e.nativeRoot,i);try{let n=await ee({root:e.nativeRoot,file:i,maxBytes:OT,label:`Native transition journal ${t}`});return qT(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ei(e,t){let i=await cf(e,t);if(!i)return null;if(i.status==="migration-required")throw new Fa(t);return i.journal}function Iw(e,t){if(Mt(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Mt(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function jw(e,t){if(Mt(e,t.nextState))return"next";if(Mt(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function BT(e){let{journal:t}=e;return Mw({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 Mw(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Ow(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=BT({sequence:a.index+1,journal:t,type:a.event.type});if(!Mt(Mw(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 mc(e,t,i){if(await Zn(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await zs(e,t);let n=await ei(e,t);if(!n)return null;let r=T(e,t),a=Ow(await Oe(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([Ne(r),Ae(e,t)]),c=Iw(o,n),l=jw(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 an(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Mt(await Ne(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 Zs(e,n.nextState,n.previousState.revision);if(!Mt(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Mt(await Ae(e,t),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await ei(e,t);if(!u||!Mt(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let d=Ow(await Oe(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(d.started||await Fi({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 Fi({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await mn({changeDir:r,run:n.nextRun,trajectoryOffset:f.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([Ne(r),Ae(e,t)]);Iw(p,{...n,previousRun:n.nextRun}),jw(m,{...n,previousState:n.nextState});let h=await ei(e,t);if(!h||!Mt(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await TT.rm(Te(e,t),{force:!0}),n.nextState}async function Fw(e,t,i){return Ie(e,`continue transition ${t}`,()=>vn(e,t,`continue transition ${t}`,()=>mc(e,t,i)))}import Lw from"node:path";var VT="comet.native.acceptance.v1",JT=/^acceptance-[a-f0-9]{64}$/u,zT=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),WT=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,UT=/^[a-f0-9]{64}$/u,KT=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function GT(e,t){return e<t?-1:e>t?1:0}var ti=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),La=Object.freeze({maxCriteria:1024}),qw="<!-- comet-native:acceptance-evidence:start -->",Bw="<!-- comet-native:acceptance-evidence:end -->";function Vw(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 Jw(e,t){let i=t.toString(36),n=M("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${n}`}function YT(e){if(!UT.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=KT.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]!==M("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function XT(e,t){let i=Vw(e.text,ti.maxTextBytes),n=e.context.slice(0,ti.maxContextItems).map(r=>Vw(r,ti.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 Ww(e){let t=YT({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],n=[...new Set(e.failedCheckIds??[])].sort(GT),r=n.slice(0,ti.maxFailedCheckIds),a=e.criteria.slice(t,t+ti.maxItems);for(let c of a){let l=[...i,XT(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?Jw(e.acceptanceHash,u):null,limits:{...ti}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>ti.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?Jw(e.acceptanceHash,o):null,limits:{...ti}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>ti.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function df(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 lf(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 zw(e){return e.includes("-->")||e.includes("--!>")}function*dr(e){let t=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
193
193
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
194
|
-
`,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=lf(l,t);else if(i)zw(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=lf(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!zw(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
|
|
194
|
+
`,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=lf(l,t);else if(i)zw(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let d=lf(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!zw(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 QT(e){return[...dr(e)].map(({line:t,body:i})=>({line:t,body:i}))}function uf(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function ZT(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function ff(e,t,i,n=[]){let r=uf(i),a=t.replaceAll("\\","/").trim(),o=n.map(uf);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-${M(VT,{kind:e,source:a,context:o,text:r})}`,kind:e,source:a,context:o,text:r}}function hf(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 e_(e){let t=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of dr(e)){r=s+1;let c=o?df(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 Uw(e,t="brief.md",i=La.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=e_(e);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of dr(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 dr(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(),hf(a.map(c=>ff("brief-example",t,c.join(`
|
|
195
195
|
`))),"Brief")}function Kw(e,t="spec.md",i=La.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(ff("spec-scenario",t,[a.title,...a.body].join(`
|
|
196
|
-
`),a.context)),a=null}};for(let{line:s,body:c}of dr(e)){let l=c?df(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=uf(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(),hf(n,"Specification")}function Gw(e,t="spec.md",i=La.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(ff("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 dr(e)){let d=u?df(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||lf(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(),hf(n,"Specification mandatory requirements")}function
|
|
197
|
-
`).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=Yw(o),c=
|
|
198
|
-
`))}function a_(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(Zw))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(Zw))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ey(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:ty(e.markdown)},markdown:e.markdown}}function o_(e,t){return iy(e.id,t.id)}function iy(e,t){return e<t?-1:e>t?1:0}function ny(e){let t=ey(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(a_).sort((d,f)=>iy(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=Uw(e.briefMarkdown,t,qa.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Kw(f,d.source,qa.maxAcceptanceCriteria-a.length)),a.push(...Gw(f,d.source,qa.maxAcceptanceCriteria-a.length)));if(a.sort(o_),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>qa.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${qa.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:ty(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(r_,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(n_,u)}}var vc={maxSpecs:64,maxFileBytes:Qr,maxTotalBytes:4*1024*1024};async function fr(e){if(e.specChanges.length>vc.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await _e({root:e.changeDir,ref:e.briefRef,maxBytes:vc.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 _e({root:e.changeDir,ref:r.source,maxBytes:vc.maxFileBytes});if(i+=a.size,i>vc.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:ny({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as k_,spawn as wF}from"node:child_process";import{promisify as E_}from"node:util";import{promises as h_}from"fs";import hr from"path";var qi={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pr=/^[a-f0-9]{64}$/u;function gc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wc(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 Li(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 ry(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pf(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function s_(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||hr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=hr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function mf(e,t){return hr.join(T(e,t),"runtime","checkpoints","progress.json")}function Bi(e,t){return hr.join(T(e,t),"runtime","checkpoint-journal.json")}function vf(e,t,i){if(!pr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return hr.join(T(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function c_(e){if(!pr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function gf(e,t,i){let n=await ee({root:e,file:t,maxBytes:qi.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function l_(e,t){let i=gc(e,`checkpoint manifest artifact ${t}`);wc(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=s_(Li(i.path,`checkpoint artifact ${t} path`,4096)),r=Tt(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!pr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:pf(i.size,`checkpoint artifact ${t} size`)}}function yc(e,t){let i=gc(e,"Native checkpoint manifest");if(wc(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>qi.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(l_),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=pf(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>qi.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 wf(e){return D(JSON.stringify(yc(e,e.change)))}function yf(e,t){let i=gc(e,"Native progress checkpoint");if(wc(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=ry(i.previousRevision,"Native checkpoint previousRevision"),a=ry(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Li(i.manifestHash,"Native checkpoint manifestHash",64);if(!pr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=c_(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Li(i.inputHash,"Native checkpoint inputHash",64);if(!pr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Li(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=pf(i.artifactCount,"Native checkpoint artifactCount");if(u>qi.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Li(i.summary,"Native checkpoint summary"),f=Li(i.nextAction,"Native checkpoint nextAction");if(St(d)!==d||St(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Li(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 u_(e,t){let i=gc(e,"Native checkpoint journal");if(wc(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=ot(i.previousState),r=ot(i.nextState),a=yf(i.checkpoint,t),o=yc(i.manifest,t),s=Li(i.inputHash,"Native checkpoint journal inputHash",64),c=D(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pr.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!==wf(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 d_(e,t,i){let n=hr.resolve(e.projectRoot,...t.split("/"));if(!B(e.projectRoot,n)||B(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=Cu(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ee({root:e.projectRoot,file:n,maxBytes:qi.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 f_(e,t){let i=mf(e,t);await I(e.nativeRoot,i);try{return yf(await gf(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Nf(e,t,i){let n=vf(e,t,i);await I(e.nativeRoot,n);let r=await gf(e.nativeRoot,n,"Native checkpoint manifest"),a=yc(r,t);if(bf(e,a),wf(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Vi(e,t){let i=Bi(e,t);await I(e.nativeRoot,i);try{let n=u_(await gf(e.nativeRoot,i,"Native checkpoint journal"),t);return bf(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ay(e,t,i,n){let r=yc(i,t);bf(e,r);let a=wf(r),o=vf(e,t,a);await I(e.nativeRoot,o);try{let s=await Nf(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 pe(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function bf(e,t){for(let i of t.artifacts){let n=Cu(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function oy(e,t){let i=yf(t,t.change),n=await Nf(e,i.change,i.manifestHash),r=D(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=mf(e,t.change);await I(e.nativeRoot,a),await pe(a,i,{containedRoot:e.nativeRoot})}async function sy(e){let t;try{t=await f_(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:mf(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 Nf(e.paths,e.name,t.manifestHash);let a=D(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 d_(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:vf(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function cy(e,t,i){let n=await Vi(e,t);if(!n)return null;if(await ay(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Zs(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await oy(e,n.checkpoint),await i?.afterProgressWritten?.(n),await h_.rm(Bi(e,t),{force:!0}),n}async function ly(e,t,i){return Ie(e,`continue checkpoint ${t}`,()=>vn(e,t,`continue checkpoint ${t}`,async()=>(await mc(e,t),cy(e,t,i))))}import{constants as Sf,promises as lt}from"node:fs";import gn from"node:path";var p_=/^[a-f0-9]{64}$/u,m_=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ba=512*1024;function v_(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function g_(e,t){let i=gn.resolve(e),n=gn.resolve(t);if(!B(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...gn.relative(i,n).split(gn.sep).filter(Boolean)]){o&&(a=gn.join(a,o));let s=await lt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await lt.realpath(a);if(r.length>0&&!B(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 uy(e){for(let t of e){let i=await lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!v_(t,i)||await lt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function w_(e){if(!p_.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function y_(e){let t=m_.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function N_(e,t,i){return gn.join(T(e,t),...w_(i).split("/"))}async function b_(e,t,i){let n=await g_(i,gn.dirname(e)),r=await lt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>Ba)throw new Error(`Native check receipt exceeds ${Ba} bytes`);let[a,o]=await Promise.all([lt.realpath(t),lt.realpath(e)]);if(!B(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Sf.O_RDONLY|Sf.O_NOFOLLOW|Sf.O_NONBLOCK,c=await lt.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(),lt.lstat(e),lt.realpath(e)]);if(await uy(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Nc(r,l)||!Nc(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=Ba+1-p,S=await c.read(m,0,Math.min(m.length,b),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>Ba)throw new Error(`Native check receipt exceeds ${Ba} bytes`);f.push(Buffer.from(m.subarray(0,S.bytesRead)))}let[h,v,N]=await Promise.all([c.stat(),lt.lstat(e),lt.realpath(e)]);if(await uy(n),!v.isFile()||v.isSymbolicLink()||N!==o||!B(a,N)||!Nc(l,h)||!Nc(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 dy(e,t,i){let n=y_(i),r=T(e,t),a=N_(e,t,n);await I(e.nativeRoot,a);let o=cc(await b_(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var IF=64*1024;var jF=3600*1e3;var OF=E_(k_);var $F=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var R_=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function fy(e,t){let i=[];for(let n of R_){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 hy(e){if(e.receipt.kind!=="static-inspection")return null;let t=await dy(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 Ji=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 P_(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 C_(e){let t=P_(e.bundle.baseline),i=await dd(e.paths,t,{origin:"explicit",now:e.now});return Od({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function my(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await $a(e.paths,e.state.name,e.state.implementation_scope),i=await fr({changeDir:T(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),n=await C_({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 vy(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await my(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 A_(e){let t=await _e({root:T(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Xw(t.text)}}function x_(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 T_(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:qd(e.implementationScope.scope.declaredArtifacts)}}async function py(e){let t=await Jd(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=fy(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 Ji([{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 hy({paths:e.paths,state:e.state,receipt:t});if(r){let a=x_({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 __(e){let t=T_({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await py({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ji)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 py({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ji)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 Ji(i)}function kf(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function bc(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:kf(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([my(e),Ha(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:kf(e.state.verification_result,"stale"),envelope:null};let n=await A_({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 __({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:kf(e.state.verification_result,"invalid"),envelope:null}}}function j_(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function wy(e){try{return await I_.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function O_(e,t){try{return(await _e({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function $_(e,t,i){let n=ec(e,i.capability);if(!B(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=gy.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await O_(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await _e({root:T(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 wy(Te(e,t))}async function Sc(e){let t=e.now??new Date,i=await Ae(e.paths,e.name),n=await qe(e.paths.projectRoot),r=j_(i.name,t),a=gy.resolve(e.paths.nativeRoot,...r.split("/"));if(!B(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=>$_(e.paths,i.name,p))),bc({paths:e.paths,state:i,now:t}),dc(e.paths,i.name),Zn(e.paths,i.name),er(e.paths,i.name),H_(e.paths,i.name),wy(a)]);return _g({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 Ef}from"node:fs";import ii from"node:path";var D_="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 by(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 yy(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 Ny(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 Sy(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await Ue({root:e,directory:t,label:`Native Archive content directory ${ii.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=yy(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=ii.join(t,u.name),f=ii.relative(e,d).replaceAll("\\","/"),p=await Ef.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()){Ny(i,{ref:f,kind:"directory"},n,r),await Sy(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 ee({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`);Ny(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await Ue({root:e,directory:t,label:`Native Archive content directory ${ii.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(yy(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${ii.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function ky(e,t={}){let i=by(t);e=ii.resolve(e);let n=await Ef.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await Sy(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 D(`${D_}\0${o}`)}async function Rt(e,t={}){let i=by(t);e=ii.resolve(e);let n;try{n=await Ef.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 ee({root:ii.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${ii.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await ky(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as $e}from"node:fs";import ce from"node:path";var Pf=16*1024*1024,F_=256*1024,L_=16*1024,Va="comet.native.archive-cas.v1";function q_(e,t){let i=ce.resolve(e.nativeRoot,...t.split("/"));if(ce.relative(e.nativeRoot,i).split(ce.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function ke(e,t){return I(e.nativeRoot,q_(e,t))}function zi(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function mr(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Ve(e){let t=await Rt(e.target);if(!zi(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${mr(t)}`);return t}async function Cf(e,t){let i=await Ot(e,t),n=await ee({root:e.nativeRoot,file:i.journal,maxBytes:F_,label:`Native Archive transaction journal ${t}`}),r=Cs(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function kc(e,t,i){let n=Cs({...t,status:i}),r=await Ot(e,n.id);return await pe(r.journal,n,{containedRoot:e.nativeRoot}),n}function Ec(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Ey(e){return{...Ec(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wi(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function B_(e,t){return Wi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Q(e){try{return await $e.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ft(e){let t=await $e.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=Ey(t),n=await ee({root:e.paths.nativeRoot,file:e.file,maxBytes:Pf,label:e.label}),r=await $e.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!B_(i,Ey(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Ec(r),size:n.size}}function V_(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!==Va||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:Va,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Lt(e,t,i,n){let r=await Ot(e,t.id),a=ce.join(r.backups,".cas"),o=`.${ce.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:ce.join(a,`${i.id}.original.json`),postRecord:ce.join(a,`${i.id}.post.json`),candidate:ce.join(a,`${i.id}.candidate`),originalQuarantine:ce.join(ce.dirname(n),`${o}.original`),rollbackQuarantine:ce.join(ce.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>I(e.nativeRoot,c))),s}async function ut(e){if(!await Q(e.file))return null;let t=await ee({root:e.paths.nativeRoot,file:e.file,maxBytes:L_,label:`Archive CAS ${e.operation.id} ${e.role} record`});return V_(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Rc(e){let t=await ut(e);if(t){if(!Wi(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await jt({root:e.paths.nativeRoot,directory:ce.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Va,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await pe(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await ut(e);if(!n||!Wi(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function fe(e){let t=await Ft({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Wi(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function J_(e){let t=await Ft({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Rc({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await fe({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function z_(e){if(!await Q(e.quarantine)||await Q(e.target))return;let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await $e.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([$e.lstat(e.quarantine),$e.lstat(e.target)]);if(!Wi(Ec(i),Ec(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await $e.unlink(e.quarantine),await t.verify()}async function Ay(e){if(await Q(e.quarantine)){await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await fe({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 fe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await $e.rename(e.target,e.quarantine),await t.verify(),await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await z_(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 wn(e){if(!await Q(e.file))return;await fe(e);let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.file),label:e.label});await t.verify(),await fe(e),await $e.unlink(e.file),await t.verify()}async function Ry(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await ke(e,t.target),r=await ke(e,t.backup),a=await Rt(r);if(a!==null){if(!zi(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Ve({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ei({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:Pf,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Ve({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function xy(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 Lt(e.paths,e.journal,e.operation,e.target),n=await ut({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await Q(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await fe({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await Ry(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await Q(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await J_({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await fe({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await Ry(e.paths,e.operation,e.hooks),await Ay({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 Py(e){let t=await Lt(e.paths,e.journal,e.operation,e.target);return await Q(t.candidate)?(await Ft({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await jt({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ei({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:Pf,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 W_(e){let t=e.operation.stagedHash,i=await Lt(e.paths,e.journal,e.operation,e.target),n=await ut({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await Q(e.target))return await fe({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await Q(i.candidate)&&await wn({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await Q(e.target)){let c=await Py(e),l=await Ft({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Ft({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Wi(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await Rc({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await wn({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await Py(e),a=await Ft({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await jt({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await fe({paths:e.paths,file:r,operation:e.operation,record:{schema:Va,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await $e.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 Ft({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Wi(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await Rc({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await wn({paths:e.paths,file:r,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}async function U_(e,t,i,n){let r=await ke(e,i.target),a=await ke(e,i.staged);if(await Ve({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Lt(e,t,i,r);(!await ut({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await Q(r))&&await xy({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await Rt(r);if(o!==null&&!zi(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${mr(o)}`)}await W_({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await Ve({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function K_(e,t,i,n){let r=await ke(e,i.target);await xy({paths:e,journal:t,operation:i,target:r,hooks:n}),await Ve({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function G_(e,t){let i=await ke(e,t.source),n=await ke(e,t.target),[r,a]=await Promise.all([Rt(i),Rt(n)]);if(!(r===null&&zi(a,t.expectedSourceHash,"directory"))){if(!zi(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${mr(r)}, target=${mr(a)}`);await $e.mkdir(ce.dirname(n),{recursive:!0}),await $e.rename(i,n),await Ve({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function Y_(e,t,i,n){return i.type==="write"?U_(e,t,i,n):i.type==="remove"?K_(e,t,i,n):G_(e,i)}function X_(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 Q_(e,t,i,n){let r=await ke(e,i.target);if(i.type==="write"){let a=await ke(e,i.staged);await Ve({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Lt(e,t,i,r),s=await ut({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 fe({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Ve({target:await ke(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await ut({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 Q(o.originalQuarantine))await fe({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 Ve({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Ve({target:await ke(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Lt(e,t,i,r),o=await ut({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 Q(a.originalQuarantine))await fe({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 Ve({target:await ke(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Ve({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Ty(e,t,i){let n=t.status==="prepared"?await kc(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await Pi(e,n.id),a=X_({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 Q_(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 it(e,n.id,"operation-started",l.id),await Y_(e,n,l,i),await it(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await Cf(e,n.id),n}async function Z_(e){try{return await fe(e),!0}catch{return!1}}async function eI(e){await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await $e.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 fe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Rf(e){if(e.operation.type!=="write")return;let t=await Lt(e.paths,e.journal,e.operation,e.target);if(!await Q(t.candidate))return;let i=await Ft({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await wn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Va,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function tI(e,t,i,n){let r=await ke(e,i.target),a=await Lt(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await ut({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await ut({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await Q(a.candidate)&&await Q(r)){let l=await Ft({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Ft({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Wi(l.identity,u.identity)&&(c=await Rc({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await Q(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await fe({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await Q(r)&&!(s!==null&&await Z_({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Rt(r);if(zi(u,o)){await Rf({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await Ay({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await Q(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await Q(r)){if(!s||!await Q(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await eI({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await Q(a.originalQuarantine)&&await wn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await Q(a.rollbackQuarantine)&&await wn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Rf({paths:e,journal:t,operation:i,target:r}),await Ve({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function iI(e,t){let i=await ke(e,t.source),n=await ke(e,t.target),[r,a]=await Promise.all([Rt(i),Rt(n)]);if(!(zi(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!zi(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${mr(r)}, target=${mr(a)}`);await $e.mkdir(ce.dirname(i),{recursive:!0}),await $e.rename(n,i)}}async function _y(e,t,i){let n=await Pi(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 kc(e,t,"rolling-back");await it(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 iI(e,o):await tI(e,r,o,i));return await it(e,r.id,"rollback-completed"),r=await kc(e,r,"rolled-back"),r}async function Cy(e,t,i){let n=await ke(e,i.target);if(i.type==="write"){let r=await Lt(e,t,i,n),a=await ut({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 fe({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Ve({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function nI(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await ke(e,i.target),r=await Lt(e,t,i,n);if(await Q(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await Cy(e,t,i),i.expectedTargetHash!==null){let a=await ut({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 Q(r.originalQuarantine)&&await wn({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Rf({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await Cy(e,t,i)}async function Pc(e,t,i){return i==="commit"&&await nI(e,t),await it(e,t.id,i),i==="commit"?kc(e,t,"committed"):t}import{promises as rI}from"fs";import aI from"path";var Af="comet.selection.v2",oI=16*1024;function Cc(e){return aI.join(e,".comet","current-change.json")}function sI(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Iy(e){return e===null||typeof e=="string"}function cI(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(!sI(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&&!Iy(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Af,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Af)throw new Error(`current change selection schema must be ${Af}`);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(!Iy(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 xf(e){let t;try{let n=Cc(e),{bytes:r}=await tn(n,oI,{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",...cI(t)}}async function jy(e){await rI.rm(Cc(e),{force:!0})}async function Oy(e,t,i){let n=await xf(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await jy(e),!0)}var jL=16*1024;async function Ac(e){let t=await xf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Xs(t.selection.change),t.selection)}function $y(e){return Cc(e.projectRoot)}async function Hy(e,t){return await Mn(e.projectRoot),Oy(e.projectRoot,"native",t)}var aq=16*1024*1024,xc=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"},Ja=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"};function Dy(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 vr.resolve(e.nativeRoot,...i.target.split("/"))}async function My(e,t,i){let n=await Pi(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(N=>N.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 Rt(Dy(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=Dy(e,t),o=vr.join(a,Se),s=await kg(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await Ne(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=Kf(Dt,c,new Set,Xd,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=Gf(Dt,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Xd,void 0)}let u=D(`archive:${t.id}:${s.name}`),d=await Oe(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"&&(!lI(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 Pc(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Vn(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await Sg(o,h)}p||(p=await Fi({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await mn({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await an(a,l),await Hy(e,s.name),t.schema==="comet.native.transaction.v2"?await Pc(e,t,"archive-finalized"):await Vn(e,t,"archive-finalized")}async function uI(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Pi(e,t.id)).some(o=>o.type==="operation-started")){let o=await Sc({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new Ja(o,"Native Archive facts changed before the first transaction operation")}let a=await Ty(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await Ae(e,t.change),c=await bc({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 My(e,a,i),Pc(e,a,"commit")}let n=await Ev(e,t);return await My(e,n,i),Vn(e,n,"commit")}function dI(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(vr.resolve(t.projectRoot)!==vr.resolve(e.projectRoot)||vr.resolve(t.nativeRoot)!==vr.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Fy(e){return Ie(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await yi(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await Ke(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await Cf(e.paths,e.transactionId):i;return dI(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?uI(e.paths,n):n.schema==="comet.native.transaction.v2"?_y(e.paths,n):xs(e.paths,n)}finally{await Ni(t)}},{allowedTransactionId:e.transactionId})}import{promises as kI}from"fs";import fI from"path";function Tf(e,t){return fI.resolve(e,...t.split(/[\\/]/u))}async function Ly(e,t){let i=[],n=T(e,t.name),r=Tf(n,Ge.stateRef),a;try{a=await Ne(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=Tf(n,a.trajectoryRef),s=await Gn(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 Oe(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=Tf(n,a.checkpointRef);try{let u=await Kn(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}var hI=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function pI(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 qy(e){let i=(e.findings??[]).filter(l=>!Yn(l.code)),n=i.find(l=>l.requiresUserDecision),r=i.find(l=>l.repairCommand!==null||hI.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:pI(e.state)}}import za from"path";var By=8,mI={"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 vI(e){let t=mI[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"}:Yn(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 gI(e,t,i){if(!i.path)return null;let n;if(za.isAbsolute(i.path)?n=za.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=za.resolve(T(e,t.name),...i.path.split(/[\\/]/u)):n=za.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!B(e.projectRoot,n))return null;let r=za.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function wI(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 Vy(e){return e.findings.map(t=>{let i=vI(t.code);return{code:t.code,message:t.message,severity:i.severity,path:gI(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:wI(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 Jy(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,By),truncated:t.length>By}}import zy from"path";var Wy=240,Uy=8,Tc=50;function Ky(e){let t=Array.from(e);return t.length<=Wy?e:`${t.slice(0,Wy-1).join("")}…`}function yI(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function NI(e){let t=[...new Set(e.map(yI))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Uy),reasonCount:e.length,codesTruncated:t.length>Uy};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Tc),reasonsTruncated:e.length>Tc}}}async function Gy(e){let t=null;try{let s=await Vi(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Bi(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:Bi(e.paths,e.state.name)}}let i=await sy({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=NI(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:qi.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Ky(i.checkpoint.summary),nextAction:Ky(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:zy.relative(e.paths.projectRoot,zy.join(T(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:qi.maxArtifacts}}async function bI(e,t){let i=T(e,t.name),n=await Ne(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 Kn(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 Oe(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function SI(e,t){let i=await bI(e,t);return{committed:i,latest:Rw(i),history:Ew(i)}}async function Yy(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await SI(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 EI=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,gr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function RI(e){try{return(await Ac(e))?.change??null}catch{return null}}function PI(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 CI(e,t){let i=T(e,t.name),n=[...(await Sd(i,t.brief)).findings,...(await Ag(e,t)).findings,...await Ly(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await Un(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 Ds(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 fr({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 ei(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 kd(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 _f(e,t,i){let n=await RI(e)===t,r;try{let w=await st(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.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:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.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:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};r=w.state}catch(w){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:w.message}}let a=await Gy({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await Yy(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let w=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:w,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 w=await fr({changeDir:T(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 E=await Ha(e,r.name,r.verification_evidence);for(let O of E.acceptanceTrace.entries)g.set(O.acceptanceId,O.status==="failed"?"failed":O.status==="missing"?"missing":"satisfied")}c=Ww({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:g,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];try{let w=await dc(e,r.name);l.push(...w.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 w=await Gs(e,r.name);if(w){let g=await pg({paths:e,identity:w});u.push(...g.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${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 w=await vy({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.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 Sc({paths:e,name:r.name}),m.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let h=[...await CI(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,g,E)=>E.findIndex(O=>O.code===w.code&&O.path===w.path)===g),v=Vy({paths:e,state:r,findings:h}),N=v.filter(w=>!Yn(w.code)),b=r.phase==="archive"&&p?.ready===!0&&N.length===0,S=f||r.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),k=v.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=v.find(w=>w.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:k||R?null:PI(r,b,S,i?.clarificationMode),archiveReady:b,inspection:a.inspection,findingSummary:Jy(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:qy({state:r,findings:v,archiveReady:b,evidenceRetreat:S,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:Tc,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}async function AI(e){let t;try{t=await ki({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await kI.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>gr.maxChanges))throw new Error(`Native status exceeds ${gr.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function Xy(e,t){let i=t.toString(36),n=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function xI(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=EI.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=M("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 TI(e,t){let i=await AI(e),n=M("comet.native.status-names.v1",i),r=xI({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+gr.maxItems).map(c=>_f(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?Xy(n,u):null,limits:{...gr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>gr.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?Xy(n,s):null,limits:{...gr}}}async function If(e,t){return(await TI(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as GI,randomUUID as YI}from"node:crypto";import{constants as Df,promises as G}from"node:fs";import re from"node:path";var jc=Vc(Zo(),1);import{randomUUID as _I}from"crypto";import{promises as iN}from"fs";import Of from"path";import{isDeepStrictEqual as $f}from"util";var yn=/^[a-f0-9]{64}$/u,II=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),jI=new Set(["sourceHash","targetHash","nextJournal"]),OI=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),Qy=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),$I=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function _c(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Zy(e){return JSON.stringify(e,null,2)+`
|
|
199
|
-
`}function Hf(e){return e.schema===ge?Qs(e):sn(e)}function jf(e,t){return{...e,schema:ge,minimum_runtime_version:2,revision:t}}function
|
|
200
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===ge?wr(a,u.previousState)||wr(a,u.nextState):a.schema===me&&(tN(a,u.previousState)||tN(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!==me)throw new Error("Schema migration transition supersede target schema is invalid");s=MI(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");_c(i.runRetreat,$I,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=_i(l.previousRun),d=_i(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!yn.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!==me||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 Ua(e,t){let i=Wa(e,t);await I(e.nativeRoot,i);try{let n=await Ss({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return FI(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function LI(e,t,i){let n=await Un(e,t),r=n?await Ds(e,n):await Ms(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=ld(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 Qn(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await fd(e,t,r)}async function nN(e){try{return await yt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function qI(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 rN(e,t){let i=t.transitionSupersede,n=T(e,t.change),r=await Oe(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&&!$f(o.event,qI(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 BI(e,t,i){if(!t.transitionSupersede)return;let n=Te(e,t.change),r=await nN(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 Ne(T(e,t.change)),o=await rN(e,t),s=await Kn(T(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!ni(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!==D(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function VI(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=T(e,t.change),a=await Ne(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ni(a,n.nextRun)){if(!ni(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await an(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!ni(await Ne(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await rN(e,t);if(o.sequence===null){let l=await Fi({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 mn({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Te(e,t.change),c=await nN(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await iN.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function JI(e,t,i){if(!t.runRetreat)return;let n=T(e,t.change),r=await Ne(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ni(r,t.runRetreat.nextRun)){if(!ni(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await an(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Oe(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Fi({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 mn({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function zI(e,t,i){let n=await Ua(e,t);if(!n)return null;if(await er(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=Of.join(T(e,t),Se),a=await yt(r);if(await BI(e,n,a===n.targetHash),await LI(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 Le(r,(0,jc.stringify)(Hf(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=Te(e,t),s=await yt(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 pe(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await VI(e,n,i),await JI(e,n,i),await iN.rm(Wa(e,t),{force:!0}),n.nextState}async function WI(e){let t=T(e.paths,e.state.name),i=await Ne(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=D(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:ge,toSchema:me,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function UI(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=wr(i,t.previousState),a=wr(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=T(e.paths,i.name),s=await Ne(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&ni(s,t.previousRun),l=ni(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 Oe(o,t.nextRun.trajectoryRef)).map((N,b)=>({event:N,index:b})).filter(({event:N})=>N.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 N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!$f(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Ic(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=D(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 yt(Te(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:h,evidenceHash:v,eventData:{fromSchema:ge,toSchema:me,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function KI(e){let t,i,n,r;if(e.state.schema===at){if(t=jf(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==on)throw new Error("Native v1 change has a transition from another schema generation");let s=HI(e.pendingTransition.journal);if(eN(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(eN(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=Te(e.paths,e.name);i={sourceHash:await yt(c),targetHash:D(Zy(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==zt)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 UI({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=DI(s);if(wr(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(wr(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=Te(e.paths,e.name);i={sourceHash:await yt(u),targetHash:D(Zy(l)),nextJournal:l}}}else t=Ic(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await WI({paths:e.paths,state:e.state,migrationId:e.id}));let a=Of.join(T(e.paths,e.name),Se),o=(0,jc.stringify)(Hf(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===at?ge:me,sourceHash:await yt(a),targetHash:D(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function aN(e){return Ie(e.paths,`migrate schema for ${e.name}`,()=>vn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await zI(e.paths,e.name,e.hooks);if(i?.schema===me)return i;let n=await st(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 er(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!==at&&r.schema!==ge)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await cf(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 KI({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??_I()}),s=Wa(e.paths,e.name);await I(e.paths.nativeRoot,s),await pe(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var ri=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),XI=512*1024,Nn=/^([a-f0-9]{64})\.json$/u,QI=/^\.([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,ZI=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Oc=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Ff(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qt(e,t){return Ff(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function uN(e,t){return Ff(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function yr(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function He(e,t){return e<t?-1:e>t?1:0}function ej(e,t){let i=re.relative(e.projectRoot,t);if(i.length===0||re.isAbsolute(i)||i===".."||i.startsWith(`..${re.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(re.sep).join("/")}function dN(e,t){return re.join(T(e,t),"runtime","evidence")}function $c(e,t){return ej(e,dN(e,t))}async function Hc(e,t){let i=re.resolve(e),n=re.resolve(t);if(!B(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=re.relative(i,n).split(re.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=re.join(o,s));let c=await G.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await G.realpath(o);if(a.length>0&&!B(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...yr(c)})}return a}async function dt(e){for(let t of e){let i=await G.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ff(t,i)||await G.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function fN(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:lr(e,t)}function oN(e){return e!==null&&ZI.test(e)?[e]:[]}function tj(e,t,i,n){if(e==="snapshots")return{canonical:nr(i,t),dependencies:[]};if(e==="scopes"){let a=rr(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=sc(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[lr("scopes",a.scopeHash)]}}if(e==="verifications"){let a=ja(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(oN));return{canonical:a,dependencies:[a.implementationScopeRef,mw(a.reportHash),...oN(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"||GI("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=lc(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=cc(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 Ui(e){let t=await G.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"?XI:Mi;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await G.realpath(e.file);if(!B(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":Df.O_RDONLY|Df.O_NOFOLLOW|Df.O_NONBLOCK,a=await G.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(),G.lstat(e.file),G.realpath(e.file)]);if(await dt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!qt(yr(t),o)||!qt(yr(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let b=i+1-d,S=await a.read(u,0,Math.min(u.length,b),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,p,m]=await Promise.all([a.stat(),G.lstat(e.file),G.realpath(e.file)]);if(await dt(e.directoryChain),!p.isFile()||p.isSymbolicLink()||m!==n||!qt(yr(o),f)||!qt(yr(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(b){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:b})}let N=tj(e.kind,e.hash,v,e.name);if(h!==JSON.stringify(N.canonical,null,2)+`
|
|
201
|
-
`)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:yr(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(He)}}finally{await a.close()}}async function sN(e){try{return await G.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function ij(e){let t=T(e.paths,e.name),i=dN(e.paths,e.name);await I(e.paths.nativeRoot,i);let n;try{let o=await Hc(t,i);n=await G.readdir(i,{withFileTypes:!0}),await dt(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of Oc){if(!n.some(d=>d.name===o))continue;let s=re.join(i,o),c=await Hc(t,s),l=(await G.readdir(s,{withFileTypes:!0})).sort((d,f)=>He(d.name,f.name)),u=new Map;for(let d of l){let f=QI.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])=>He(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=re.join(s,d),h=Nn.exec(d)?.[1];if(!h)throw new Error(`Native evidence cleanup quarantine name is invalid: ${p.name}`);let v=fN(o,h),N=re.join(s,p.name),b=await Ui({changeRoot:t,file:N,ref:v,kind:o,hash:h,name:e.name,directoryChain:c}),S=await sN(m),k=S?null:await Ui({changeRoot:t,file:m,ref:v,kind:o,hash:h,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:N,document:b,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(He);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Nr(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${Dc(a)}`),path:$c(e.paths,e.name)}]};for(let o of r.sort((s,c)=>He(s.ref,c.ref))){if(await dt(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Ui({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Ui({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!qt(o.originalDocument.identity,u.identity)||!qt(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await G.rm(o.quarantine),await dt(o.document.directoryChain);continue}if(!await sN(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await G.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!qt(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await G.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Ui({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Ui({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!uN(o.document.identity,c.identity)||!qt(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await G.rm(o.quarantine),await dt(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Nr(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Dc(a)}`),path:$c(e.paths,e.name)}]}}async function nj(e,t){let i=T(e,t),n=re.join(i,"runtime","evidence");await I(e.nativeRoot,n);let r;try{let c=await Hc(i,n);r=await G.readdir(n,{withFileTypes:!0}),await dt(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!Oc.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(He);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Dc(a)}`);let o=[],s=0;for(let c of Oc){if(!r.some(f=>f.name===c))continue;let l=re.join(n,c),u=await Hc(i,l),d=(await G.readdir(l,{withFileTypes:!0})).sort((f,p)=>He(f.name,p.name));await dt(u);for(let f of d){if(o.length>=ri.maxDocuments)throw new Error(`Native evidence store exceeds ${ri.maxDocuments} documents`);let p=Nn.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=fN(c,p[1]),h=re.join(l,f.name);await I(e.nativeRoot,h);let v=await Ui({changeRoot:i,file:h,ref:m,kind:c,hash:p[1],name:t,directoryChain:u});if(s+=v.size,s>ri.maxScannedBytes)throw new Error(`Native evidence store exceeds ${ri.maxScannedBytes} scanned bytes`);o.push(v)}await dt(u)}return o}function cN(e,t){let i=new Set,n=[...e].sort(He).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(He).reverse())i.has(o)||n.push(o)}return i}function rj(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(He),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(He))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function aj(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=cN(t,n),a=new Set(r);for(let c of e)i-c.mtimeMs<ri.minimumAgeMs&&a.add(c.ref);for(let c of Oc){let l=e.filter(u=>u.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||He(u.ref,d.ref)).slice(0,ri.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=cN(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=ri.minimumAgeMs).sort((c,l)=>He(c.ref,l.ref));return{candidates:rj(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Dc(e){let t=e.slice(0,ri.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Nr(e){let t=ri.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 Mf(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(He);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Nr(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Dc(r)}`),path:n}}async function lN(e,t){try{await G.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await G.rename(e,t)}catch{}}async function oj(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await dt(e.directoryChain);let i=await Ui({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Nn.exec(re.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await G.lstat(e.file),r=await G.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!qt(e.identity,n)||!qt(e.identity,i.identity)||!B(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=re.join(re.dirname(e.file),`.${re.basename(e.file)}.${YI()}.gc`);await G.rename(e.file,a);try{let[o,s]=await Promise.all([G.lstat(a),G.realpath(a)]);if(await dt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!uN(e.identity,o)||!B(e.directoryChain[0].realPath,s))throw await lN(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await G.rm(a),await dt(e.directoryChain)}catch(o){throw await lN(a,e.file),o}}async function sj(e){if((await qe(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await G.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 Ke(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function cj(e,t){if(t)return[t];let i;try{i=await G.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(He)}async function lj(e,t){let i=await st(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([ei(e,t),Ua(e,t),Vi(e,t)]);return n!==null||r!==null||a!==null}async function uj(e){if(await lj(e.paths,e.name))return[];let t=await st(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await ij({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 nj(e.paths,e.name),a=aj(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=$c(e.paths,e.name);if(!e.repair)return[...i.findings,Mf(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await oj(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Mf(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Nr(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Mf(e.name,a,!0,o)]}async function hN(e){if(e.deferAll||await sj(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 cj(e.paths,e.name))try{a.push(...await uj({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Nr(`Native evidence retention refused to clean ${o}: ${s.message}`),path:$c(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 Ie(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Nr(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as dj,randomUUID as LB}from"crypto";import{promises as Ya}from"fs";import te from"path";var qf=64*1024*1024,fj=256*1024,gN=16*1024*1024;async function De(e){try{return await Ya.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hj(e){let t;try{t=await Ya.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 st(e,i.name)}catch{continue}n.status!=="current"||!n.state||!("revision"in n.state)||await Ks({paths:e,name:i.name,revision:n.state.revision})}}async function Ga(e,t){let i=[];async function n(r){let a=await Ue({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=te.join(r,s.name);if(t.excludedFiles?.has(te.resolve(c))){await a.verify();continue}let l=await Ya.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:te.relative(e,c).split(te.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await ee({root:e,file:c,maxBytes:qf,label:`Native root file ${te.relative(e,c)}`});i.push({ref:te.relative(e,c).split(te.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 pj(e,t,i,n){await jt({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await Ue({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=te.join(a,l.name);if(te.resolve(u)===te.resolve(i)){await s.verify();continue}let d=await Ya.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=te.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await jt({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ei({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:qf,label:`Native root move file ${te.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 br(e,t,i,n){let r=await Ga(e,{rejectSymlinks:!0,excludedFiles:i?new Set([te.resolve(i)]):void 0}),a=await Ga(t,{rejectSymlinks:!0,excludedFiles:n?new Set([te.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 mj(e,t){return te.join(e.artifactRoot,`.comet-native-move-${t}`)}function vj(e,t){return te.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function gj(e){return`${e}.removing`}function pN(e,t){return te.join(te.dirname(e),`.${te.basename(e)}.${t}.rollback-removing`)}function wN(e,t,i){return te.join(As(e,t).directory,`root-move-cleanup-${i}.json`)}function wj(e){return JSON.stringify(e,null,2)+`
|
|
202
|
-
`}function yj(e){return dj("sha256").update(e).digest("hex")}function Nj(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("\\")||te.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 bj(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(Nj);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=te.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 Sj(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=wj(t);if(Buffer.byteLength(i,"utf8")>gN)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await Le(wN(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),yj(i)}async function kj(e){let t=await ee({root:e.paths.nativeRoot,file:wN(e.paths,e.id,e.cleanup.kind),maxBytes:gN,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 bj(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Lf(e){let t=await Ga(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 mN(e){return e.ref.split("/").length}async function Ej(e){let i=[...await Lf({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>mN(a)-mN(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=te.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await ks({root:e.projectRoot,file:a,maxBytes:qf,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await Wu({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 Lf({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Wu({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function yN(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function Rj(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 Pj(e,t,i,n){for(let a of[e,t])try{let o=await Ke(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=te.join(i,"runtime","transactions",n,"transaction.json");try{let a=await ee({root:i,file:r,maxBytes:fj,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 vN(e){let t=yN(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await la(e.projectRoot,t),t}async function Ka(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=yN(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 la(e.projectRoot,i),i}async function Mc(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 De(e.target),a=await De(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 Sj({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ga(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await Ka({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await kj({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await De(e.target),a=await De(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 fv({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 Ka({projectRoot:e.projectRoot,config:t,id:e.id})}return await Lf({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await Ka({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await Ka({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await Ej({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Ka({projectRoot:e.projectRoot,config:t,id:e.id})}async function Cj(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await De(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=gj(e.staging);t=await Mc({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 Ga(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([te.resolve(e.lockFile)])}),await pj(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await br(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await vN({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await De(e.destinationPaths.nativeRoot)){if(await De(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await br(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await De(e.staging))throw new Error("Native move staging tree is missing");await br(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ya.rename(e.staging,e.destinationPaths.nativeRoot)}t=await vN({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 De(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=vj(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await De(e.sourcePaths.nativeRoot)&&await br(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Mc({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 hj(e.destinationPaths);let r=await Ke(e.destinationPaths,e.pending.id);await Vn(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 la(e.projectRoot,o),o}async function NN(e){let t=await qe(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await _t(e.projectRoot,i.fromArtifactRoot),r=await _t(e.projectRoot,i.toArtifactRoot),a=mj(r,i.id),o=await De(n.nativeRoot)?n:r,s=await yi(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await Pj(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await De(n.nativeRoot))throw m;let h=Rj({id:i.id,paths:n,now:new Date});await Sv(n,h),c={journal:h,paths:n}}if(e.strategy==="continue"){let m=await Cj({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 De(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=pN(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await De(r.nativeRoot)&&await br(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Mc({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=pN(a,i.id);!t.native.pending_root_move?.cleanup&&await De(a)&&await br(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Mc({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 Ke(n,i.id);await xs(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 la(e.projectRoot,p),{activeNativeRoot:n.nativeRoot,config:p}}finally{await Ni(s)}}var Xa=4096,xj=4096,Tj=1024;async function bn(e,t,i){try{let n=await Ue({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 Fc(e,t){let i=new Map(e.map(n=>[we.resolve(n.file),{...n,file:we.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await ua(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 zu(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 _j(e,t){let i=$y(e),n;try{await I(e.projectRoot,i);let r=await Ac(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 Ae(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 Aj.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 Ij(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await I(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 jj(e,t){let i=[],n=[];for(let r of await bn(e,e.transactionsDir,xj)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await Ke(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:we.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 Ns([e],`doctor archive recovery ${a.id}`,async()=>await Fc([{paths:e,file:we.join(e.locksDir,"root-move.lock")},{paths:e,file:we.join(e.locksDir,"archive.lock")}],i)?(await Fy({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 Oj(e,t,i){let n=[];for(let r of await bn(e,e.locksDir,Tj)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=we.join(e.locksDir,r.name);try{let o=await ua(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 zu(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 $j(e,t,i=5){let n=[],r=t?await If(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await If(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:we.join(e.changesDir,a.name,Se)});continue}let o=await _f(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:we.join(e.projectRoot,s.path)}:{}})}return n}async function Hj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await Gn(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 og(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:we.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function Dj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await vd(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:Xn(e,r),repair:"migrate"});continue}let a=await Ae(e,r);await hg({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:Xn(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:Xn(e,r)})}return i}async function Mj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Wa(e,r);try{let o=await Ua(e,r),s=await st(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:we.join(e.changesDir,r,Se)});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:we.join(e.changesDir,r,Se),repair:"migrate"});continue}await aN({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:we.join(e.changesDir,r,Se)})}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 Fj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await ei(e,r)}catch(o){if(o instanceof Fa)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Te(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Ns([e],`doctor transition recovery ${r}`,async()=>await Fc([{paths:e,file:we.join(e.locksDir,"root-move.lock")},{paths:e,file:we.join(e.locksDir,`transition-${r}.lock`)}],i)?(await Fw(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:Te(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Te(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:Te(e,r),repair:"continue"})}}return i}async function Lj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Bi(e,r),o;try{o=await Vi(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 Ns([e],`doctor checkpoint recovery ${r}`,async()=>await Fc([{paths:e,file:we.join(e.locksDir,"root-move.lock")},{paths:e,file:we.join(e.locksDir,`transition-${r}.lock`)}],i)?(await ly(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 bN(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await qe(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([_t(n.projectRoot,c.fromArtifactRoot),_t(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Fc([{paths:l,file:we.join(l.locksDir,"root-move.lock")},{paths:u,file:we.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await NN({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await _t(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 Ij(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await jj(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await Mj(n,{name:e.name,repair:t})),i.push(...await Dj(n,{name:e.name,repair:t})),i.push(...await Hj(n,{name:e.name,repair:t})),i.push(...await Fj(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await Lj(n,{name:e.name,repair:t})),i.push(...await hN({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await Oj(n,t,s.unfinished)),i.push(...await _j(n,t)),i.push(...await $j(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import qj from"path";var PV=10*1024*1024,ai=class extends Error{};function Lc(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new ai(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function qc(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new ai(`${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 ai(`${t} requires a value`);return e.splice(n,2),r}function SN(e){if(e.length>0)throw new ai(`Unexpected argument: ${e[0]}`)}async function kN(e){return e?qj.resolve(e):Lu(process.cwd())}async function EN(e){let t=await qe(e);return _t(e,t?.native.artifact_root??"docs")}function RN(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
196
|
+
`),a.context)),a=null}};for(let{line:s,body:c}of dr(e)){let l=c?df(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=uf(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(),hf(n,"Specification")}function Gw(e,t="spec.md",i=La.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(ff("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 dr(e)){let d=u?df(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||lf(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(),hf(n,"Specification mandatory requirements")}function t_(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||ZT(i)||Lw.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=Lw.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(!WT.test(n))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return n}function i_(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=>!zT.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${n.join(", ")}`);return i}function Yw(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=i_(i,n),a=r.acceptance_id;if(typeof a!="string"||!JT.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 t_(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 Xw(e){let t=QT(e);if(t.some(({line:l,body:u})=>!u&&(l===qw||l===Bw)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=t.flatMap(({line:l,body:u},d)=>u&&l===qw?[d]:[]),r=t.flatMap(({line:l,body:u},d)=>u&&l===Bw?[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
|
+
`).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=Yw(o),c=n_(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function n_(e){let t=Yw([...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)}import Qw from"node:path";var r_="comet.native.contract.v1",a_="comet.native.acceptance-set.v1",Zw=/^[a-f0-9]{64}$/u,qa={maxAcceptanceCriteria:La.maxCriteria};function ey(e,t){let i=Qw.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})||Qw.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 ty(e){return M("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
198
|
+
`))}function o_(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(Zw))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(Zw))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=ey(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:ty(e.markdown)},markdown:e.markdown}}function s_(e,t){return iy(e.id,t.id)}function iy(e,t){return e<t?-1:e>t?1:0}function ny(e){let t=ey(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(o_).sort((d,f)=>iy(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=Uw(e.briefMarkdown,t,qa.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...Kw(f,d.source,qa.maxAcceptanceCriteria-a.length)),a.push(...Gw(f,d.source,qa.maxAcceptanceCriteria-a.length)));if(a.sort(s_),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>qa.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${qa.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:ty(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=M(a_,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:M(r_,u)}}var vc={maxSpecs:64,maxFileBytes:Qr,maxTotalBytes:4*1024*1024};async function fr(e){if(e.specChanges.length>vc.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await _e({root:e.changeDir,ref:e.briefRef,maxBytes:vc.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 _e({root:e.changeDir,ref:r.source,maxBytes:vc.maxFileBytes});if(i+=a.size,i>vc.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:ny({briefSource:t.ref,briefMarkdown:t.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{execFile as E_,spawn as y1}from"node:child_process";import{promisify as R_}from"node:util";import{promises as p_}from"fs";import hr from"path";var qi={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},pr=/^[a-f0-9]{64}$/u;function gc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wc(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 Li(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 ry(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pf(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function c_(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||hr.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=hr.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function mf(e,t){return hr.join(T(e,t),"runtime","checkpoints","progress.json")}function Bi(e,t){return hr.join(T(e,t),"runtime","checkpoint-journal.json")}function vf(e,t,i){if(!pr.test(i))throw new Error("Native checkpoint manifest hash is invalid");return hr.join(T(e,t),"runtime","checkpoints","manifests",`${i}.json`)}function l_(e){if(!pr.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function gf(e,t,i){let n=await ee({root:e,file:t,maxBytes:qi.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function u_(e,t){let i=gc(e,`checkpoint manifest artifact ${t}`);wc(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let n=c_(Li(i.path,`checkpoint artifact ${t} path`,4096)),r=Tt(n);if(r)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!pr.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:n,hash:i.hash,size:pf(i.size,`checkpoint artifact ${t} size`)}}function yc(e,t){let i=gc(e,"Native checkpoint manifest");if(wc(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>qi.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(u_),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=pf(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>qi.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 wf(e){return D(JSON.stringify(yc(e,e.change)))}function yf(e,t){let i=gc(e,"Native progress checkpoint");if(wc(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=ry(i.previousRevision,"Native checkpoint previousRevision"),a=ry(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Li(i.manifestHash,"Native checkpoint manifestHash",64);if(!pr.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=l_(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Li(i.inputHash,"Native checkpoint inputHash",64);if(!pr.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Li(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=pf(i.artifactCount,"Native checkpoint artifactCount");if(u>qi.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Li(i.summary,"Native checkpoint summary"),f=Li(i.nextAction,"Native checkpoint nextAction");if(St(d)!==d||St(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Li(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 d_(e,t){let i=gc(e,"Native checkpoint journal");if(wc(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=ot(i.previousState),r=ot(i.nextState),a=yf(i.checkpoint,t),o=yc(i.manifest,t),s=Li(i.inputHash,"Native checkpoint journal inputHash",64),c=D(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!pr.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!==wf(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 f_(e,t,i){let n=hr.resolve(e.projectRoot,...t.split("/"));if(!B(e.projectRoot,n)||B(e.nativeRoot,n))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let r=Cu(e,t);if(r)throw new Error(`Checkpoint artifact is excluded as sensitive (${r}): ${t}`);let a=await ee({root:e.projectRoot,file:n,maxBytes:qi.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 h_(e,t){let i=mf(e,t);await I(e.nativeRoot,i);try{return yf(await gf(e.nativeRoot,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Nf(e,t,i){let n=vf(e,t,i);await I(e.nativeRoot,n);let r=await gf(e.nativeRoot,n,"Native checkpoint manifest"),a=yc(r,t);if(bf(e,a),wf(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Vi(e,t){let i=Bi(e,t);await I(e.nativeRoot,i);try{let n=d_(await gf(e.nativeRoot,i,"Native checkpoint journal"),t);return bf(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ay(e,t,i,n){let r=yc(i,t);bf(e,r);let a=wf(r),o=vf(e,t,a);await I(e.nativeRoot,o);try{let s=await Nf(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 pe(o,r,{containedRoot:e.nativeRoot,beforeCommit:n?.beforeCommit}),a}function bf(e,t){for(let i of t.artifacts){let n=Cu(e,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function oy(e,t){let i=yf(t,t.change),n=await Nf(e,i.change,i.manifestHash),r=D(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=mf(e,t.change);await I(e.nativeRoot,a),await pe(a,i,{containedRoot:e.nativeRoot})}async function sy(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:mf(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 Nf(e.paths,e.name,t.manifestHash);let a=D(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 f_(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:vf(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:r,freshness:i.length===0?"fresh":"stale",reasons:i,findings:n}}async function cy(e,t,i){let n=await Vi(e,t);if(!n)return null;if(await ay(e,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Zs(e,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await oy(e,n.checkpoint),await i?.afterProgressWritten?.(n),await p_.rm(Bi(e,t),{force:!0}),n}async function ly(e,t,i){return Ie(e,`continue checkpoint ${t}`,()=>vn(e,t,`continue checkpoint ${t}`,async()=>(await mc(e,t),cy(e,t,i))))}import{constants as Sf,promises as lt}from"node:fs";import gn from"node:path";var m_=/^[a-f0-9]{64}$/u,v_=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ba=512*1024;function g_(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nc(e,t){let i={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return Ee(i,n)?L(i,n):L(i,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function w_(e,t){let i=gn.resolve(e),n=gn.resolve(t);if(!B(i,n))throw new Error("Native check receipt parent is outside the Native root");let r=[],a=i;for(let o of["",...gn.relative(i,n).split(gn.sep).filter(Boolean)]){o&&(a=gn.join(a,o));let s=await lt.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await lt.realpath(a);if(r.length>0&&!B(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 uy(e){for(let t of e){let i=await lt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!g_(t,i)||await lt.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function y_(e){if(!m_.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function N_(e){let t=v_.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function b_(e,t,i){return gn.join(T(e,t),...y_(i).split("/"))}async function S_(e,t,i){let n=await w_(i,gn.dirname(e)),r=await lt.lstat(e);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(r.size>Ba)throw new Error(`Native check receipt exceeds ${Ba} bytes`);let[a,o]=await Promise.all([lt.realpath(t),lt.realpath(e)]);if(!B(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Sf.O_RDONLY|Sf.O_NOFOLLOW|Sf.O_NONBLOCK,c=await lt.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(),lt.lstat(e),lt.realpath(e)]);if(await uy(n),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Nc(r,l)||!Nc(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,m=Buffer.allocUnsafe(16*1024);for(;;){let b=Ba+1-p,S=await c.read(m,0,Math.min(m.length,b),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>Ba)throw new Error(`Native check receipt exceeds ${Ba} bytes`);f.push(Buffer.from(m.subarray(0,S.bytesRead)))}let[h,v,N]=await Promise.all([c.stat(),lt.lstat(e),lt.realpath(e)]);if(await uy(n),!v.isFile()||v.isSymbolicLink()||N!==o||!B(a,N)||!Nc(l,h)||!Nc(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 dy(e,t,i){let n=N_(i),r=T(e,t),a=b_(e,t,n);await I(e.nativeRoot,a);let o=cc(await S_(a,r,e.nativeRoot));if(o.change!==t||o.receiptHash!==n)throw new Error("Native check receipt ref/hash/change mismatch");return o}var j1=64*1024;var O1=3600*1e3;var $1=R_(E_);var H1=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");var P_=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function fy(e,t){let i=[];for(let n of P_){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 hy(e){if(e.receipt.kind!=="static-inspection")return null;let t=await dy(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 Ji=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 C_(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 A_(e){let t=C_(e.bundle.baseline),i=await dd(e.paths,t,{origin:"explicit",now:e.now});return Od({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason}).scope.currentProjectionHash}async function my(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await $a(e.paths,e.state.name,e.state.implementation_scope),i=await fr({changeDir:T(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 vy(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await my(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 x_(e){let t=await _e({root:T(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Xw(t.text)}}function T_(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 __(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:qd(e.implementationScope.scope.declaredArtifacts)}}async function py(e){let t=await Jd(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let n=fy(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 Ji([{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 hy({paths:e.paths,state:e.state,receipt:t});if(r){let a=T_({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 I_(e){let t=__({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let n of e.requiredReceiptRefs){let r=await py({...e,ref:n,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Ji)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 py({...e,result:n.status==="passed"?"pass":"fail",ref:r,expectedBindings:t,acceptanceId:n.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Ji)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 Ji(i)}function kf(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function bc(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:kf(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([my(e),Ha(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:kf(e.state.verification_result,"stale"),envelope:null};let n=await x_({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 I_({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:kf(e.state.verification_result,"invalid"),envelope:null}}}function O_(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function wy(e){try{return await j_.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $_(e,t){try{return(await _e({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function H_(e,t,i){let n=ec(e,i.capability);if(!B(e.nativeRoot,n))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let r=gy.relative(e.nativeRoot,n).replaceAll("\\","/"),a=await $_(e.nativeRoot,r),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await _e({root:T(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 D_(e,t){return wy(Te(e,t))}async function Sc(e){let t=e.now??new Date,i=await Ae(e.paths,e.name),n=await qe(e.paths.projectRoot),r=O_(i.name,t),a=gy.resolve(e.paths.nativeRoot,...r.split("/"));if(!B(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=>H_(e.paths,i.name,p))),bc({paths:e.paths,state:i,now:t}),dc(e.paths,i.name),Zn(e.paths,i.name),er(e.paths,i.name),D_(e.paths,i.name),wy(a)]);return _g({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 Ef}from"node:fs";import ii from"node:path";var M_="comet.native.archive-tree.v1",F_={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function by(e){let t={...F_,...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 yy(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 Ny(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 Sy(e,t,i,n,r,a){if(a>r.maxDepth)throw new Error(`Native Archive content exceeds depth ${r.maxDepth}`);let o=await Ue({root:e,directory:t,label:`Native Archive content directory ${ii.relative(e,t)||"."}`,maxEntries:r.maxEntries}),s=yy(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=ii.join(t,u.name),f=ii.relative(e,d).replaceAll("\\","/"),p=await Ef.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()){Ny(i,{ref:f,kind:"directory"},n,r),await Sy(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 ee({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`);Ny(i,{ref:f,kind:"file",hash:m.hash,size:m.size},n,r),await o.verify()}await o.verify();let l=await Ue({root:e,directory:t,label:`Native Archive content directory ${ii.relative(e,t)||"."}`,maxEntries:r.maxEntries});if(yy(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${ii.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function ky(e,t={}){let i=by(t);e=ii.resolve(e);let n=await Ef.lstat(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let r=[];await Sy(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 D(`${M_}\0${o}`)}async function Rt(e,t={}){let i=by(t);e=ii.resolve(e);let n;try{n=await Ef.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 ee({root:ii.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${ii.basename(e)}`})).hash};if(n.isDirectory())return{kind:"directory",hash:await ky(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as $e}from"node:fs";import ce from"node:path";var Pf=16*1024*1024,L_=256*1024,q_=16*1024,Va="comet.native.archive-cas.v1";function B_(e,t){let i=ce.resolve(e.nativeRoot,...t.split("/"));if(ce.relative(e.nativeRoot,i).split(ce.sep).includes(".."))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return i}async function ke(e,t){return I(e.nativeRoot,B_(e,t))}function zi(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function mr(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function Ve(e){let t=await Rt(e.target);if(!zi(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${mr(t)}`);return t}async function Cf(e,t){let i=await Ot(e,t),n=await ee({root:e.nativeRoot,file:i.journal,maxBytes:L_,label:`Native Archive transaction journal ${t}`}),r=Cs(JSON.parse(n.bytes.toString("utf8")));if(r.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return r}async function kc(e,t,i){let n=Cs({...t,status:i}),r=await Ot(e,n.id);return await pe(r.journal,n,{containedRoot:e.nativeRoot}),n}function Ec(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function Ey(e){return{...Ec(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wi(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function V_(e,t){return Wi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Q(e){try{return await $e.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ft(e){let t=await $e.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=Ey(t),n=await ee({root:e.paths.nativeRoot,file:e.file,maxBytes:Pf,label:e.label}),r=await $e.lstat(e.file);if(!r.isFile()||r.isSymbolicLink()||!V_(i,Ey(r))||n.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Ec(r),size:n.size}}function J_(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!==Va||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:Va,operationId:t.id,role:i,hash:n,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Lt(e,t,i,n){let r=await Ot(e,t.id),a=ce.join(r.backups,".cas"),o=`.${ce.basename(n)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:ce.join(a,`${i.id}.original.json`),postRecord:ce.join(a,`${i.id}.post.json`),candidate:ce.join(a,`${i.id}.candidate`),originalQuarantine:ce.join(ce.dirname(n),`${o}.original`),rollbackQuarantine:ce.join(ce.dirname(n),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>I(e.nativeRoot,c))),s}async function ut(e){if(!await Q(e.file))return null;let t=await ee({root:e.paths.nativeRoot,file:e.file,maxBytes:q_,label:`Archive CAS ${e.operation.id} ${e.role} record`});return J_(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Rc(e){let t=await ut(e);if(t){if(!Wi(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await jt({root:e.paths.nativeRoot,directory:ce.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Va,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await pe(e.file,i,{containedRoot:e.paths.nativeRoot,exclusive:!0})}catch(r){if(r.code!=="EEXIST")throw r}let n=await ut(e);if(!n||!Wi(n.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return n}async function fe(e){let t=await Ft({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Wi(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function z_(e){let t=await Ft({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Rc({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await fe({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function W_(e){if(!await Q(e.quarantine)||await Q(e.target))return;let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await $e.link(e.quarantine,e.target)}catch(r){if(r.code==="EEXIST")return;throw r}await t.verify();let[i,n]=await Promise.all([$e.lstat(e.quarantine),$e.lstat(e.target)]);if(!Wi(Ec(i),Ec(n)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await $e.unlink(e.quarantine),await t.verify()}async function Ay(e){if(await Q(e.quarantine)){await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await fe({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 fe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await $e.rename(e.target,e.quarantine),await t.verify(),await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await W_(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 wn(e){if(!await Q(e.file))return;await fe(e);let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.file),label:e.label});await t.verify(),await fe(e),await $e.unlink(e.file),await t.verify()}async function Ry(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let n=await ke(e,t.target),r=await ke(e,t.backup),a=await Rt(r);if(a!==null){if(!zi(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await Ve({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ei({sourceRoot:e.nativeRoot,source:n,targetRoot:e.nativeRoot,target:r,maxBytes:Pf,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await Ve({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function xy(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 Lt(e.paths,e.journal,e.operation,e.target),n=await ut({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await Q(i.originalQuarantine)){if(!n)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await fe({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:n,label:`Archive apply quarantine ${e.operation.target}`}),await Ry(e.paths,e.operation,e.hooks),{record:n,quarantine:i.originalQuarantine}}if(!await Q(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return n??=await z_({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await fe({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive apply target ${e.operation.target}`}),await Ry(e.paths,e.operation,e.hooks),await Ay({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 Py(e){let t=await Lt(e.paths,e.journal,e.operation,e.target);return await Q(t.candidate)?(await Ft({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await jt({root:e.paths.nativeRoot,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ei({sourceRoot:e.paths.nativeRoot,source:e.staged,targetRoot:e.paths.nativeRoot,target:t.candidate,maxBytes:Pf,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 U_(e){let t=e.operation.stagedHash,i=await Lt(e.paths,e.journal,e.operation,e.target),n=await ut({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(n&&await Q(e.target))return await fe({paths:e.paths,file:e.target,operation:e.operation,record:n,label:`Archive write target ${e.operation.target}`}),await Q(i.candidate)&&await wn({paths:e.paths,file:i.candidate,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n;if(await Q(e.target)){let c=await Py(e),l=await Ft({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Ft({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Wi(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return n=await Rc({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await wn({paths:e.paths,file:c,operation:e.operation,record:n,label:`Archive write candidate ${e.operation.target}`}),n}let r=await Py(e),a=await Ft({paths:e.paths,file:r,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await jt({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await fe({paths:e.paths,file:r,operation:e.operation,record:{schema:Va,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await $e.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 Ft({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Wi(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return n=await Rc({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await wn({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 ke(e,i.target),a=await ke(e,i.staged);if(await Ve({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Lt(e,t,i,r);(!await ut({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await Q(r))&&await xy({paths:e,journal:t,operation:i,target:r,hooks:n})}else{let o=await Rt(r);if(o!==null&&!zi(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${mr(o)}`)}await U_({paths:e,journal:t,operation:i,staged:a,target:r,hooks:n}),await Ve({target:r,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function G_(e,t,i,n){let r=await ke(e,i.target);await xy({paths:e,journal:t,operation:i,target:r,hooks:n}),await Ve({target:r,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function Y_(e,t){let i=await ke(e,t.source),n=await ke(e,t.target),[r,a]=await Promise.all([Rt(i),Rt(n)]);if(!(r===null&&zi(a,t.expectedSourceHash,"directory"))){if(!zi(r,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${mr(r)}, target=${mr(a)}`);await $e.mkdir(ce.dirname(n),{recursive:!0}),await $e.rename(i,n),await Ve({target:n,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function X_(e,t,i,n){return i.type==="write"?K_(e,t,i,n):i.type==="remove"?G_(e,t,i,n):Y_(e,i)}function Q_(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 Z_(e,t,i,n){let r=await ke(e,i.target);if(i.type==="write"){let a=await ke(e,i.staged);await Ve({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Lt(e,t,i,r),s=await ut({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 fe({paths:e,file:r,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await Ve({target:await ke(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await ut({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 Q(o.originalQuarantine))await fe({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 Ve({target:r,expectedHash:null,label:`Completed Archive target ${i.target}`}),await Ve({target:await ke(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Lt(e,t,i,r),o=await ut({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 Q(a.originalQuarantine))await fe({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 Ve({target:await ke(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await Ve({target:r,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function Ty(e,t,i){let n=t.status==="prepared"?await kc(e,t,"applying"):t;if(n.status!=="applying")throw new Error(`Native Archive transaction ${n.id} cannot apply from ${n.status}`);let r=await Pi(e,n.id),a=Q_({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 Z_(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 it(e,n.id,"operation-started",l.id),await X_(e,n,l,i),await it(e,n.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return n=await Cf(e,n.id),n}async function eI(e){try{return await fe(e),!0}catch{return!1}}async function tI(e){await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await ki({root:e.paths.nativeRoot,directory:ce.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await fe({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await $e.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 fe({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Rf(e){if(e.operation.type!=="write")return;let t=await Lt(e.paths,e.journal,e.operation,e.target);if(!await Q(t.candidate))return;let i=await Ft({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await wn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Va,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function iI(e,t,i,n){let r=await ke(e,i.target),a=await Lt(e,t,i,r),o=i.expectedTargetHash,s=o===null?null:await ut({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await ut({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await Q(a.candidate)&&await Q(r)){let l=await Ft({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await Ft({paths:e,file:r,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Wi(l.identity,u.identity)&&(c=await Rc({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await Q(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await fe({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await Q(r)&&!(s!==null&&await eI({paths:e,file:r,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await Rt(r);if(zi(u,o)){await Rf({paths:e,journal:t,operation:i,target:r});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await Ay({paths:e,operation:i,phase:"rollback",target:r,quarantine:a.rollbackQuarantine,record:c,hooks:n})}if(o===null){if(await Q(r))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await Q(r)){if(!s||!await Q(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await tI({paths:e,operation:i,target:r,quarantine:a.originalQuarantine,record:s,hooks:n})}s&&await Q(a.originalQuarantine)&&await wn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await Q(a.rollbackQuarantine)&&await wn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Rf({paths:e,journal:t,operation:i,target:r}),await Ve({target:r,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function nI(e,t){let i=await ke(e,t.source),n=await ke(e,t.target),[r,a]=await Promise.all([Rt(i),Rt(n)]);if(!(zi(r,t.expectedSourceHash,"directory")&&a===null)){if(r!==null||!zi(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${mr(r)}, target=${mr(a)}`);await $e.mkdir(ce.dirname(i),{recursive:!0}),await $e.rename(n,i)}}async function _y(e,t,i){let n=await Pi(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 kc(e,t,"rolling-back");await it(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 nI(e,o):await iI(e,r,o,i));return await it(e,r.id,"rollback-completed"),r=await kc(e,r,"rolled-back"),r}async function Cy(e,t,i){let n=await ke(e,i.target);if(i.type==="write"){let r=await Lt(e,t,i,n),a=await ut({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 fe({paths:e,file:n,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await Ve({target:n,expectedHash:null,label:`Archive commit target ${i.target}`})}async function rI(e,t){for(let i of t.operations){if(i.type==="move")continue;let n=await ke(e,i.target),r=await Lt(e,t,i,n);if(await Q(r.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await Cy(e,t,i),i.expectedTargetHash!==null){let a=await ut({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 Q(r.originalQuarantine)&&await wn({paths:e,file:r.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Rf({paths:e,journal:t,operation:i,target:n})}for(let i of t.operations)i.type!=="move"&&await Cy(e,t,i)}async function Pc(e,t,i){return i==="commit"&&await rI(e,t),await it(e,t.id,i),i==="commit"?kc(e,t,"committed"):t}import{promises as aI}from"fs";import oI from"path";var Af="comet.selection.v2",sI=16*1024;function Cc(e){return oI.join(e,".comet","current-change.json")}function cI(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Iy(e){return e===null||typeof e=="string"}function lI(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(!cI(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&&!Iy(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Af,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Af)throw new Error(`current change selection schema must be ${Af}`);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(!Iy(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 xf(e){let t;try{let n=Cc(e),{bytes:r}=await tn(n,sI,{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",...lI(t)}}async function jy(e){await aI.rm(Cc(e),{force:!0})}async function Oy(e,t,i){let n=await xf(e);return n.status!=="selected"||n.selection.workflow!==t||n.selection.change!==i?!1:(await jy(e),!0)}var OL=16*1024;async function Ac(e){let t=await xf(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Xs(t.selection.change),t.selection)}function $y(e){return Cc(e.projectRoot)}async function Hy(e,t){return await Mn(e.projectRoot),Oy(e.projectRoot,"native",t)}var oq=16*1024*1024,xc=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"},Ja=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"};function Dy(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 vr.resolve(e.nativeRoot,...i.target.split("/"))}async function My(e,t,i){let n=await Pi(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(N=>N.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 Rt(Dy(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=Dy(e,t),o=vr.join(a,Se),s=await kg(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=await Ne(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=Kf(Dt,c,new Set,Xd,void 0);if(!h.action)throw new Error(h.reason??"Native archive produced no action");l=Gf(Dt,h.state,{actionId:h.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Xd,void 0)}let u=D(`archive:${t.id}:${s.name}`),d=await Oe(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"&&(!uI(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 Pc(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Vn(e,t,"archive-finalization-started")),!s.archived){let h={...s,archived:!0};await Sg(o,h)}p||(p=await Fi({changeDir:a,run:l,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await mn({changeDir:a,run:l,trajectoryOffset:p.sequence,evidenceHash:u,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await an(a,l),await Hy(e,s.name),t.schema==="comet.native.transaction.v2"?await Pc(e,t,"archive-finalized"):await Vn(e,t,"archive-finalized")}async function dI(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Pi(e,t.id)).some(o=>o.type==="operation-started")){let o=await Sc({paths:e,name:t.change,now:new Date(t.createdAt)});if(!o.ready||o.preflightHash!==t.preflightHash)throw new Ja(o,"Native Archive facts changed before the first transaction operation")}let a=await Ty(e,t,{...i,beforeArchiveChangeMove:async o=>{await i?.beforeArchiveChangeMove?.(o);let s=await Ae(e,t.change),c=await bc({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 My(e,a,i),Pc(e,a,"commit")}let n=await Ev(e,t);return await My(e,n,i),Vn(e,n,"commit")}function fI(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(vr.resolve(t.projectRoot)!==vr.resolve(e.projectRoot)||vr.resolve(t.nativeRoot)!==vr.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Fy(e){return Ie(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await yi(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await Ke(e.paths,e.transactionId),n=i.schema==="comet.native.transaction.v2"?await Cf(e.paths,e.transactionId):i;return fI(e.paths,n),n.status==="committed"||n.status==="rolled-back"?n:e.strategy==="continue"?dI(e.paths,n):n.schema==="comet.native.transaction.v2"?_y(e.paths,n):xs(e.paths,n)}finally{await Ni(t)}},{allowedTransactionId:e.transactionId})}import{promises as EI}from"fs";import hI from"path";function Tf(e,t){return hI.resolve(e,...t.split(/[\\/]/u))}async function Ly(e,t){let i=[],n=T(e,t.name),r=Tf(n,Ge.stateRef),a;try{a=await Ne(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=Tf(n,a.trajectoryRef),s=await Gn(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 Oe(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=Tf(n,a.checkpointRef);try{let u=await Kn(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}var pI=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function mI(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 qy(e){let i=(e.findings??[]).filter(l=>!Yn(l.code)),n=i.find(l=>l.requiresUserDecision),r=i.find(l=>l.repairCommand!==null||pI.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:mI(e.state)}}import za from"path";var By=8,vI={"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 gI(e){let t=vI[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"}:Yn(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 wI(e,t,i){if(!i.path)return null;let n;if(za.isAbsolute(i.path)?n=za.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?n=za.resolve(T(e,t.name),...i.path.split(/[\\/]/u)):n=za.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!B(e.projectRoot,n))return null;let r=za.relative(e.projectRoot,n).replaceAll("\\","/");return r===""?".":r}function yI(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 Vy(e){return e.findings.map(t=>{let i=gI(t.code);return{code:t.code,message:t.message,severity:i.severity,path:wI(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:yI(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 Jy(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,By),truncated:t.length>By}}import zy from"path";var Wy=240,Uy=8,Tc=50;function Ky(e){let t=Array.from(e);return t.length<=Wy?e:`${t.slice(0,Wy-1).join("")}…`}function NI(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function bI(e){let t=[...new Set(e.map(NI))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,Uy),reasonCount:e.length,codesTruncated:t.length>Uy};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Tc),reasonsTruncated:e.length>Tc}}}async function Gy(e){let t=null;try{let s=await Vi(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Bi(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:Bi(e.paths,e.state.name)}}let i=await sy({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),n=t?[t.code,...i.reasons]:i.reasons,r=bI(n);if(!i.checkpoint)return{inspection:r.inspection,inspectionDetails:r.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:qi.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:Ky(i.checkpoint.summary),nextAction:Ky(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:zy.relative(e.paths.projectRoot,zy.join(T(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:qi.maxArtifacts}}async function SI(e,t){let i=T(e,t.name),n=await Ne(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 Kn(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 Oe(i,n.trajectoryRef),committedTrajectoryOffset:r.trajectoryOffset,runId:n.runId}}async function kI(e,t){let i=await SI(e,t);return{committed:i,latest:Rw(i),history:Ew(i)}}async function Yy(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let n=await kI(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 RI=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,gr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});async function PI(e){try{return(await Ac(e))?.change??null}catch{return null}}function CI(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 AI(e,t){let i=T(e,t.name),n=[...(await Sd(i,t.brief)).findings,...(await Ag(e,t)).findings,...await Ly(e,t)];if(t.phase==="shape"||t.phase==="build")try{let r=await Un(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 Ds(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 fr({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 ei(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 kd(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 _f(e,t,i){let n=await PI(e)===t,r;try{let w=await st(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.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:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.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:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};r=w.state}catch(w){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:w.message}}let a=await Gy({paths:e,state:r}),o=null,s=[];if(r.phase==="build"&&r.verification_result==="fail")try{if(o=await Yy(e,r,i?.maxVerifyFailures??5),o&&(o.disposition==="manual-stop"||o.disposition==="hard-stop")){let w=o.disposition==="hard-stop"?"repair-iteration-limit":o.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";s.push({code:w,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 w=await fr({changeDir:T(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 E=await Ha(e,r.name,r.verification_evidence);for(let O of E.acceptanceTrace.entries)g.set(O.acceptanceId,O.status==="failed"?"failed":O.status==="missing"?"missing":"satisfied")}c=Ww({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:g,failedCheckIds:o?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}})}catch(w){if(i.acceptanceCursor)throw w;c=void 0}let l=[];try{let w=await dc(e,r.name);l.push(...w.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 w=await Gs(e,r.name);if(w){let g=await pg({paths:e,identity:w});u.push(...g.findingCodes.map(E=>({code:E,message:`Native workspace advisory changed: ${E} (${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 w=await vy({paths:e,state:r});f=w.freshness!=="fresh",d.push(...w.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 Sc({paths:e,name:r.name}),m.push(...p.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let h=[...await AI(e,r),...a.findings,...l,...u,...d,...s,...m].filter((w,g,E)=>E.findIndex(O=>O.code===w.code&&O.path===w.path)===g),v=Vy({paths:e,state:r,findings:h}),N=v.filter(w=>!Yn(w.code)),b=r.phase==="archive"&&p?.ready===!0&&N.length===0,S=f||r.phase==="archive"&&(p?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),k=v.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"),R=o?.disposition==="manual-stop"||o?.disposition==="hard-stop",y=v.find(w=>w.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:k||R?null:CI(r,b,S,i?.clarificationMode),archiveReady:b,inspection:a.inspection,findingSummary:Jy(v),detailsCommand:`comet native status ${r.name} --details`,checkpoint:a.checkpoint,continuation:qy({state:r,findings:v,archiveReady:b,evidenceRetreat:S,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:Tc,maxCheckpointArtifacts:a.maxCheckpointArtifacts,findingsTruncated:v.length>50,inspectionReasonsTruncated:a.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,...y?{error:y.message}:{}}}async function xI(e){let t;try{t=await ki({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[],n=await EI.opendir(e.changesDir);try{for await(let r of n)if(!(!r.isDirectory()||r.isSymbolicLink())&&(i.push(r.name),i.length>gr.maxChanges))throw new Error(`Native status exceeds ${gr.maxChanges} visible changes`)}finally{await n.close().catch(r=>{if(r.code!=="ERR_DIR_CLOSED")throw r})}return await t.verify(),i.sort()}function Xy(e,t){let i=t.toString(36),n=M("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${n}`}function TI(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=RI.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=M("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 _I(e,t){let i=await xI(e),n=M("comet.native.status-names.v1",i),r=TI({namesHash:n,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(r,r+gr.maxItems).map(c=>_f(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?Xy(n,u):null,limits:{...gr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>gr.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?Xy(n,s):null,limits:{...gr}}}async function If(e,t){return(await _I(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as YI,randomUUID as XI}from"node:crypto";import{constants as Df,promises as G}from"node:fs";import re from"node:path";var jc=Vc(Zo(),1);import{randomUUID as II}from"crypto";import{promises as iN}from"fs";import Of from"path";import{isDeepStrictEqual as $f}from"util";var yn=/^[a-f0-9]{64}$/u,jI=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),OI=new Set(["sourceHash","targetHash","nextJournal"]),$I=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),Qy=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),HI=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function _c(e,t,i){let n=Object.keys(e).find(r=>!t.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function Zy(e){return JSON.stringify(e,null,2)+`
|
|
199
|
+
`}function Hf(e){return e.schema===ge?Qs(e):sn(e)}function jf(e,t){return{...e,schema:ge,minimum_runtime_version:2,revision:t}}function DI(e){return{...e,schema:zt,minimum_runtime_version:2,revision:1,previousState:jf(e.previousState,1),nextState:jf(e.nextState,2)}}function Ic(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:me,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 MI(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?D(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:ji,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:Ic(e.previousState),nextState:{...Ic(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Dt.definition.metadata.version,skillHash:Ma}:e.nextRun}}function eN(e,t){return JSON.stringify(e)===JSON.stringify(t)}function wr(e,t){return JSON.stringify(Qs(e))===JSON.stringify(Qs(t))}function tN(e,t){return JSON.stringify(sn(e))===JSON.stringify(sn(t))}function ni(e,t){return $f(e,t)}function FI(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(_c(r,$I,"Schema migration transition supersede plan"),typeof r.sourceHash!="string"||!yn.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"||!yn.test(r.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=_i(r.previousRun),o=_i(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||!ni(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!==Qy.size||u.some(f=>!Qy.has(f))||l.fromSchema!==ge||l.toSchema!==me||!["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=D(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 Wa(e,t){return Of.join(T(e,t),"runtime","schema-migration.json")}function LI(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");_c(e,jI,"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===at&&i.toSchema===ge,r=i.fromSchema===ge&&i.toSchema===me;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"||!yn.test(i.sourceHash)||typeof i.targetHash!="string"||!yn.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?Oi(i.nextState):ot(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(D((0,jc.stringify)(Hf(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");_c(i.transition,OI,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!yn.test(l.sourceHash)||typeof l.targetHash!="string"||!yn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=n?sf(l.nextJournal,t):of(l.nextJournal,t);if(D(JSON.stringify(l.nextJournal,null,2)+`
|
|
200
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(n&&a.schema===ge?wr(a,u.previousState)||wr(a,u.nextState):a.schema===me&&(tN(a,u.previousState)||tN(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!==me)throw new Error("Schema migration transition supersede target schema is invalid");s=FI(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");_c(i.runRetreat,HI,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=_i(l.previousRun),d=_i(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!yn.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!==me||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 Ua(e,t){let i=Wa(e,t);await I(e.nativeRoot,i);try{let n=await Ss({root:e.nativeRoot,file:i,maxBytes:524288,label:"Native schema migration journal"});return LI(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function qI(e,t,i){let n=await Un(e,t),r=n?await Ds(e,n):await Ms(e,{now:new Date(i),origin:"legacy-migration"});if(!r.complete){let a=ld(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 Qn(t,r.omittedCount,o,a.samplePaths,a.sampleTruncated)}n===null&&await fd(e,t,r)}async function nN(e){try{return await yt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function BI(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 rN(e,t){let i=t.transitionSupersede,n=T(e,t.change),r=await Oe(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&&!$f(o.event,BI(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 VI(e,t,i){if(!t.transitionSupersede)return;let n=Te(e,t.change),r=await nN(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 Ne(T(e,t.change)),o=await rN(e,t),s=await Kn(T(e,t.change),t.transitionSupersede.nextRun.checkpointRef);if(!i||!a||!ni(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!==D(t.transitionSupersede.evidenceHash)||s.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function JI(e,t,i){let n=t.transitionSupersede;if(!n)return;let r=T(e,t.change),a=await Ne(r);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ni(a,n.nextRun)){if(!ni(a,n.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await an(r,n.nextRun),await i?.afterRunStateWritten?.(t)}if(!ni(await Ne(r),n.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await rN(e,t);if(o.sequence===null){let l=await Fi({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 mn({changeDir:r,run:n.nextRun,trajectoryOffset:o.sequence,evidenceHash:n.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Te(e,t.change),c=await nN(s);if(c!==null){if(c!==n.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await iN.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function zI(e,t,i){if(!t.runRetreat)return;let n=T(e,t.change),r=await Ne(n);if(!r)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ni(r,t.runRetreat.nextRun)){if(!ni(r,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await an(n,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await Oe(n,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Fi({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 mn({changeDir:n,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function WI(e,t,i){let n=await Ua(e,t);if(!n)return null;if(await er(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let r=Of.join(T(e,t),Se),a=await yt(r);if(await VI(e,n,a===n.targetHash),await qI(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 Le(r,(0,jc.stringify)(Hf(n.nextState))),await i?.afterStateWritten?.(n)}if(n.transition){let o=Te(e,t),s=await yt(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 pe(o,n.transition.nextJournal),await i?.afterTransitionWritten?.(n)}}return await JI(e,n,i),await zI(e,n,i),await iN.rm(Wa(e,t),{force:!0}),n.nextState}async function UI(e){let t=T(e.paths,e.state.name),i=await Ne(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=D(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:n,evidenceHash:r,eventData:{fromSchema:ge,toSchema:me,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function KI(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=wr(i,t.previousState),a=wr(i,t.nextState);if(!r&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=T(e.paths,i.name),s=await Ne(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&ni(s,t.previousRun),l=ni(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 Oe(o,t.nextRun.trajectoryRef)).map((N,b)=>({event:N,index:b})).filter(({event:N})=>N.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 N={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!$f(f.event,N)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Ic(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=D(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 yt(Te(e.paths,i.name)),transitionId:t.id,previousRun:m,nextRun:h,evidenceHash:v,eventData:{fromSchema:ge,toSchema:me,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function GI(e){let t,i,n,r;if(e.state.schema===at){if(t=jf(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==on)throw new Error("Native v1 change has a transition from another schema generation");let s=DI(e.pendingTransition.journal);if(eN(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(eN(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=Te(e.paths,e.name);i={sourceHash:await yt(c),targetHash:D(Zy(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==zt)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 KI({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,n=l.plan}else{let l=MI(s);if(wr(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(wr(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=Te(e.paths,e.name);i={sourceHash:await yt(u),targetHash:D(Zy(l)),nextJournal:l}}}else t=Ic(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(r=await UI({paths:e.paths,state:e.state,migrationId:e.id}));let a=Of.join(T(e.paths,e.name),Se),o=(0,jc.stringify)(Hf(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===at?ge:me,sourceHash:await yt(a),targetHash:D(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...n?{transitionSupersede:n}:{},...r?{runRetreat:r}:{}}}async function aN(e){return Ie(e.paths,`migrate schema for ${e.name}`,()=>vn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await WI(e.paths,e.name,e.hooks);if(i?.schema===me)return i;let n=await st(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 er(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!==at&&r.schema!==ge)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await cf(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 GI({paths:e.paths,name:e.name,state:r,pendingTransition:a,now:e.now??new Date,id:e.id?.()??II()}),s=Wa(e.paths,e.name);await I(e.paths.nativeRoot,s),await pe(s,o),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var ri=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),QI=512*1024,Nn=/^([a-f0-9]{64})\.json$/u,ZI=/^\.([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,ej=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Oc=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Ff(e,t){return L({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function qt(e,t){return Ff(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function uN(e,t){return Ff(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function yr(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function He(e,t){return e<t?-1:e>t?1:0}function tj(e,t){let i=re.relative(e.projectRoot,t);if(i.length===0||re.isAbsolute(i)||i===".."||i.startsWith(`..${re.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(re.sep).join("/")}function dN(e,t){return re.join(T(e,t),"runtime","evidence")}function $c(e,t){return tj(e,dN(e,t))}async function Hc(e,t){let i=re.resolve(e),n=re.resolve(t);if(!B(i,n))throw new Error("Native evidence retention path escapes its managed change");let r=re.relative(i,n).split(re.sep).filter(Boolean),a=[],o=i;for(let s of["",...r]){s&&(o=re.join(o,s));let c=await G.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await G.realpath(o);if(a.length>0&&!B(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...yr(c)})}return a}async function dt(e){for(let t of e){let i=await G.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ff(t,i)||await G.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function fN(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:lr(e,t)}function oN(e){return e!==null&&ej.test(e)?[e]:[]}function ij(e,t,i,n){if(e==="snapshots")return{canonical:nr(i,t),dependencies:[]};if(e==="scopes"){let a=rr(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=sc(i);if(a.change!==n||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[lr("scopes",a.scopeHash)]}}if(e==="verifications"){let a=ja(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(oN));return{canonical:a,dependencies:[a.implementationScopeRef,mw(a.reportHash),...oN(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"||YI("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=lc(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=cc(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 Ui(e){let t=await G.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"?QI:Mi;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let n=await G.realpath(e.file);if(!B(e.directoryChain[0].realPath,n))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let r=process.platform==="win32"?"r":Df.O_RDONLY|Df.O_NOFOLLOW|Df.O_NONBLOCK,a=await G.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(),G.lstat(e.file),G.realpath(e.file)]);if(await dt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==n||!qt(yr(t),o)||!qt(yr(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let b=i+1-d,S=await a.read(u,0,Math.min(u.length,b),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,p,m]=await Promise.all([a.stat(),G.lstat(e.file),G.realpath(e.file)]);if(await dt(e.directoryChain),!p.isFile()||p.isSymbolicLink()||m!==n||!qt(yr(o),f)||!qt(yr(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(b){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:b})}let N=ij(e.kind,e.hash,v,e.name);if(h!==JSON.stringify(N.canonical,null,2)+`
|
|
201
|
+
`)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:yr(f),directoryChain:e.directoryChain,dependencies:[...new Set(N.dependencies)].sort(He)}}finally{await a.close()}}async function sN(e){try{return await G.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function nj(e){let t=T(e.paths,e.name),i=dN(e.paths,e.name);await I(e.paths.nativeRoot,i);let n;try{let o=await Hc(t,i);n=await G.readdir(i,{withFileTypes:!0}),await dt(o)}catch(o){if(o.code==="ENOENT")return{findings:[],pending:!1};throw o}let r=[];for(let o of Oc){if(!n.some(d=>d.name===o))continue;let s=re.join(i,o),c=await Hc(t,s),l=(await G.readdir(s,{withFileTypes:!0})).sort((d,f)=>He(d.name,f.name)),u=new Map;for(let d of l){let f=ZI.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])=>He(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=re.join(s,d),h=Nn.exec(d)?.[1];if(!h)throw new Error(`Native evidence cleanup quarantine name is invalid: ${p.name}`);let v=fN(o,h),N=re.join(s,p.name),b=await Ui({changeRoot:t,file:N,ref:v,kind:o,hash:h,name:e.name,directoryChain:c}),S=await sN(m),k=S?null:await Ui({changeRoot:t,file:m,ref:v,kind:o,hash:h,name:e.name,directoryChain:c});r.push({ref:v,original:m,quarantine:N,document:b,action:S?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(r.length===0)return{findings:[],pending:!1};let a=r.map(o=>o.ref).sort(He);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Nr(`Native evidence cleanup has ${a.length} safely recoverable quarantined document(s) for ${e.name}: ${Dc(a)}`),path:$c(e.paths,e.name)}]};for(let o of r.sort((s,c)=>He(s.ref,c.ref))){if(await dt(o.document.directoryChain),o.action==="finish-linked-recovery"){let u=await Ui({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),d=await Ui({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!o.originalDocument||!qt(o.originalDocument.identity,u.identity)||!qt(o.document.identity,d.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${o.ref}`);await G.rm(o.quarantine),await dt(o.document.directoryChain);continue}if(!await sN(o.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${o.ref}`);let s=await G.lstat(o.quarantine);if(!s.isFile()||s.isSymbolicLink()||!qt(o.document.identity,s))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${o.ref}`);await G.link(o.quarantine,o.original),await e.hooks.afterRecoveryLink?.({ref:o.ref,original:o.original,quarantine:o.quarantine});let c=await Ui({changeRoot:t,file:o.original,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain}),l=await Ui({changeRoot:t,file:o.quarantine,ref:o.ref,kind:o.document.kind,hash:Nn.exec(re.basename(o.original))[1],name:e.name,directoryChain:o.document.directoryChain});if(!uN(o.document.identity,c.identity)||!qt(c.identity,l.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${o.ref}`);await G.rm(o.quarantine),await dt(o.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Nr(`Recovered ${a.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Dc(a)}`),path:$c(e.paths,e.name)}]}}async function rj(e,t){let i=T(e,t),n=re.join(i,"runtime","evidence");await I(e.nativeRoot,n);let r;try{let c=await Hc(i,n);r=await G.readdir(n,{withFileTypes:!0}),await dt(c)}catch(c){if(c.code==="ENOENT")return[];throw c}let a=r.filter(c=>!Oc.includes(c.name)||!c.isDirectory()||c.isSymbolicLink()).map(c=>c.name).sort(He);if(a.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Dc(a)}`);let o=[],s=0;for(let c of Oc){if(!r.some(f=>f.name===c))continue;let l=re.join(n,c),u=await Hc(i,l),d=(await G.readdir(l,{withFileTypes:!0})).sort((f,p)=>He(f.name,p.name));await dt(u);for(let f of d){if(o.length>=ri.maxDocuments)throw new Error(`Native evidence store exceeds ${ri.maxDocuments} documents`);let p=Nn.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=fN(c,p[1]),h=re.join(l,f.name);await I(e.nativeRoot,h);let v=await Ui({changeRoot:i,file:h,ref:m,kind:c,hash:p[1],name:t,directoryChain:u});if(s+=v.size,s>ri.maxScannedBytes)throw new Error(`Native evidence store exceeds ${ri.maxScannedBytes} scanned bytes`);o.push(v)}await dt(u)}return o}function cN(e,t){let i=new Set,n=[...e].sort(He).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(He).reverse())i.has(o)||n.push(o)}return i}function aj(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(He),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(He))}}if(r.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return r}function oj(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=cN(t,n),a=new Set(r);for(let c of e)i-c.mtimeMs<ri.minimumAgeMs&&a.add(c.ref);for(let c of Oc){let l=e.filter(u=>u.kind===c&&!r.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||He(u.ref,d.ref)).slice(0,ri.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=cN(a,n),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=ri.minimumAgeMs).sort((c,l)=>He(c.ref,l.ref));return{candidates:aj(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Dc(e){let t=e.slice(0,ri.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Nr(e){let t=ri.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 Mf(e,t,i,n){let r=t.candidates.map(a=>a.ref).sort(He);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Nr(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Dc(r)}`),path:n}}async function lN(e,t){try{await G.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await G.rename(e,t)}catch{}}async function sj(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await dt(e.directoryChain);let i=await Ui({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Nn.exec(re.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),n=await G.lstat(e.file),r=await G.realpath(e.file);if(!n.isFile()||n.isSymbolicLink()||!qt(e.identity,n)||!qt(e.identity,i.identity)||!B(e.directoryChain[0].realPath,r))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=re.join(re.dirname(e.file),`.${re.basename(e.file)}.${XI()}.gc`);await G.rename(e.file,a);try{let[o,s]=await Promise.all([G.lstat(a),G.realpath(a)]);if(await dt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!uN(e.identity,o)||!B(e.directoryChain[0].realPath,s))throw await lN(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await G.rm(a),await dt(e.directoryChain)}catch(o){throw await lN(a,e.file),o}}async function cj(e){if((await qe(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await G.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 Ke(e,n.name);if(r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}}return!1}async function lj(e,t){if(t)return[t];let i;try{i=await G.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(He)}async function uj(e,t){let i=await st(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[n,r,a]=await Promise.all([ei(e,t),Ua(e,t),Vi(e,t)]);return n!==null||r!==null||a!==null}async function dj(e){if(await uj(e.paths,e.name))return[];let t=await st(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await nj({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 rj(e.paths,e.name),a=oj(r,n,e.nowMs);if(a.candidates.length===0)return i.findings;let o=$c(e.paths,e.name);if(!e.repair)return[...i.findings,Mf(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await sj(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Mf(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Nr(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Mf(e.name,a,!0,o)]}async function hN(e){if(e.deferAll||await cj(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 lj(e.paths,e.name))try{a.push(...await dj({paths:e.paths,name:o,repair:r,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Nr(`Native evidence retention refused to clean ${o}: ${s.message}`),path:$c(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 Ie(e.paths,"prune Native evidence",()=>i(!0))}catch(r){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Nr(`Native evidence cleanup was deferred until the project mutation lock is available: ${r.message}`)}]}}import{createHash as fj,randomUUID as qB}from"crypto";import{promises as Ya}from"fs";import te from"path";var qf=64*1024*1024,hj=256*1024,gN=16*1024*1024;async function De(e){try{return await Ya.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pj(e){let t;try{t=await Ya.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 st(e,i.name)}catch{continue}n.status!=="current"||!n.state||!("revision"in n.state)||await Ks({paths:e,name:i.name,revision:n.state.revision})}}async function Ga(e,t){let i=[];async function n(r){let a=await Ue({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=te.join(r,s.name);if(t.excludedFiles?.has(te.resolve(c))){await a.verify();continue}let l=await Ya.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:te.relative(e,c).split(te.sep).join("/"),type:"directory"}),await n(c);else if(s.isFile()&&l.isFile()){let u=await ee({root:e,file:c,maxBytes:qf,label:`Native root file ${te.relative(e,c)}`});i.push({ref:te.relative(e,c).split(te.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 mj(e,t,i,n){await jt({root:n,directory:t,label:"Native root move staging directory"});async function r(a,o){let s=await Ue({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=te.join(a,l.name);if(te.resolve(u)===te.resolve(i)){await s.verify();continue}let d=await Ya.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=te.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await jt({root:n,directory:f,label:"Native root move staging directory"}),await r(u,f);else if(l.isFile()&&d.isFile())await Ei({sourceRoot:e,source:u,targetRoot:n,target:f,maxBytes:qf,label:`Native root move file ${te.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 br(e,t,i,n){let r=await Ga(e,{rejectSymlinks:!0,excludedFiles:i?new Set([te.resolve(i)]):void 0}),a=await Ga(t,{rejectSymlinks:!0,excludedFiles:n?new Set([te.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 vj(e,t){return te.join(e.artifactRoot,`.comet-native-move-${t}`)}function gj(e,t){return te.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function wj(e){return`${e}.removing`}function pN(e,t){return te.join(te.dirname(e),`.${te.basename(e)}.${t}.rollback-removing`)}function wN(e,t,i){return te.join(As(e,t).directory,`root-move-cleanup-${i}.json`)}function yj(e){return JSON.stringify(e,null,2)+`
|
|
202
|
+
`}function Nj(e){return fj("sha256").update(e).digest("hex")}function bj(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("\\")||te.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 Sj(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(bj);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=te.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 kj(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=yj(t);if(Buffer.byteLength(i,"utf8")>gN)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await Le(wN(e.paths,e.id,e.kind),i,{containedRoot:e.paths.nativeRoot}),Nj(i)}async function Ej(e){let t=await ee({root:e.paths.nativeRoot,file:wN(e.paths,e.id,e.cleanup.kind),maxBytes:gN,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 Sj(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Lf(e){let t=await Ga(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 mN(e){return e.ref.split("/").length}async function Rj(e){let i=[...await Lf({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((r,a)=>mN(a)-mN(r)||(r.type===a.type?a.ref.localeCompare(r.ref):r.type==="file"?-1:1)),n=0;for(let r of i){let a=te.join(e.quarantine,...r.ref.split("/"));r.type==="file"?await ks({root:e.projectRoot,file:a,maxBytes:qf,expectedHash:r.hash,expectedSize:r.size,label:`Native root-move cleanup file ${r.ref}`}):await Wu({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 Lf({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Wu({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function yN(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function Pj(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 Cj(e,t,i,n){for(let a of[e,t])try{let o=await Ke(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=te.join(i,"runtime","transactions",n,"transaction.json");try{let a=await ee({root:i,file:r,maxBytes:hj,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 vN(e){let t=yN(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await la(e.projectRoot,t),t}async function Ka(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=yN(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 la(e.projectRoot,i),i}async function Mc(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 De(e.target),a=await De(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 kj({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ga(e.target,{rejectSymlinks:!0})});n={kind:e.kind,state:"prepared",manifestHash:s},t=await Ka({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})}let o=await Ej({paths:e.stablePaths,id:e.id,cleanup:n});if(r=await De(e.target),a=await De(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 fv({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 Ka({projectRoot:e.projectRoot,config:t,id:e.id})}return await Lf({quarantine:e.quarantine,manifest:o,exact:n.state!=="deleting"}),n.state==="prepared"&&(n={...n,state:"quarantined"},t=await Ka({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),n.state==="quarantined"&&(n={...n,state:"deleting"},t=await Ka({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:n})),await Rj({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Ka({projectRoot:e.projectRoot,config:t,id:e.id})}async function Aj(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await De(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=wj(e.staging);t=await Mc({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 Ga(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([te.resolve(e.lockFile)])}),await mj(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await br(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await vN({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await De(e.destinationPaths.nativeRoot)){if(await De(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await br(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await De(e.staging))throw new Error("Native move staging tree is missing");await br(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ya.rename(e.staging,e.destinationPaths.nativeRoot)}t=await vN({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 De(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let n=gj(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await De(e.sourcePaths.nativeRoot)&&await br(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Mc({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 pj(e.destinationPaths);let r=await Ke(e.destinationPaths,e.pending.id);await Vn(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 la(e.projectRoot,o),o}async function NN(e){let t=await qe(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let n=await _t(e.projectRoot,i.fromArtifactRoot),r=await _t(e.projectRoot,i.toArtifactRoot),a=vj(r,i.id),o=await De(n.nativeRoot)?n:r,s=await yi(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await Cj(n,r,a,i.id)}catch(m){if(i.stage!=="copying"||!await De(n.nativeRoot))throw m;let h=Pj({id:i.id,paths:n,now:new Date});await Sv(n,h),c={journal:h,paths:n}}if(e.strategy==="continue"){let m=await Aj({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 De(n.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=pN(r.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await De(r.nativeRoot)&&await br(n.nativeRoot,r.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Mc({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=pN(a,i.id);!t.native.pending_root_move?.cleanup&&await De(a)&&await br(n.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Mc({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 Ke(n,i.id);await xs(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 la(e.projectRoot,p),{activeNativeRoot:n.nativeRoot,config:p}}finally{await Ni(s)}}var Xa=4096,Tj=4096,_j=1024;async function bn(e,t,i){try{let n=await Ue({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 Fc(e,t){let i=new Map(e.map(n=>[we.resolve(n.file),{...n,file:we.resolve(n.file)}]));for(let{paths:n,file:r}of i.values()){let a;try{a=await ua(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 zu(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 Ij(e,t){let i=$y(e),n;try{await I(e.projectRoot,i);let r=await Ac(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 Ae(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 xj.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 jj(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await I(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 Oj(e,t){let i=[],n=[];for(let r of await bn(e,e.transactionsDir,Tj)){if(!r.isDirectory()||r.isSymbolicLink())continue;let a;try{a=await Ke(e,r.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${r.name} is invalid: ${o.message}`,path:we.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 Ns([e],`doctor archive recovery ${a.id}`,async()=>await Fc([{paths:e,file:we.join(e.locksDir,"root-move.lock")},{paths:e,file:we.join(e.locksDir,"archive.lock")}],i)?(await Fy({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 $j(e,t,i){let n=[];for(let r of await bn(e,e.locksDir,_j)){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".lock"))continue;let a=we.join(e.locksDir,r.name);try{let o=await ua(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 zu(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 Hj(e,t,i=5){let n=[],r=t?await If(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await If(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:we.join(e.changesDir,a.name,Se)});continue}let o=await _f(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:we.join(e.projectRoot,s.path)}:{}})}return n}async function Dj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{let a=await Gn(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 og(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:we.join(e.changesDir,r,"runtime","trajectory.jsonl")})}return i}async function Mj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n)try{if(!await vd(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:Xn(e,r),repair:"migrate"});continue}let a=await Ae(e,r);await hg({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:Xn(e,r)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${r}: ${a.message}`,path:Xn(e,r)})}return i}async function Fj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Wa(e,r);try{let o=await Ua(e,r),s=await st(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:we.join(e.changesDir,r,Se)});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:we.join(e.changesDir,r,Se),repair:"migrate"});continue}await aN({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:we.join(e.changesDir,r,Se)})}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 Lj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a;try{a=await ei(e,r)}catch(o){if(o instanceof Fa)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Te(e,r)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Ns([e],`doctor transition recovery ${r}`,async()=>await Fc([{paths:e,file:we.join(e.locksDir,"root-move.lock")},{paths:e,file:we.join(e.locksDir,`transition-${r}.lock`)}],i)?(await Fw(e,r),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${r}`,path:Te(e,r)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Te(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:Te(e,r),repair:"continue"})}}return i}async function qj(e,t){let i=[],n=t.name?[t.name]:(await bn(e,e.changesDir,Xa)).filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort();for(let r of n){let a=Bi(e,r),o;try{o=await Vi(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 Ns([e],`doctor checkpoint recovery ${r}`,async()=>await Fc([{paths:e,file:we.join(e.locksDir,"root-move.lock")},{paths:e,file:we.join(e.locksDir,`transition-${r}.lock`)}],i)?(await ly(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 bN(e){let t=e.repair??!1,i=[],n=e.paths,r;try{r=await qe(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([_t(n.projectRoot,c.fromArtifactRoot),_t(n.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Fc([{paths:l,file:we.join(l.locksDir,"root-move.lock")},{paths:u,file:we.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await NN({projectRoot:n.projectRoot,strategy:e.recoveryStrategy});n=await _t(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 jj(n);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await Oj(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),i.push(...await Fj(n,{name:e.name,repair:t})),i.push(...await Mj(n,{name:e.name,repair:t})),i.push(...await Dj(n,{name:e.name,repair:t})),i.push(...await Lj(n,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await qj(n,{name:e.name,repair:t})),i.push(...await hN({paths:n,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0})),i.push(...await $j(n,t,s.unfinished)),i.push(...await Ij(n,t)),i.push(...await Hj(n,e.name,r?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import Bj from"path";var CV=10*1024*1024,ai=class extends Error{};function Lc(e,t){let i=e.flatMap((n,r)=>n===t?[r]:[]);if(i.length>1)throw new ai(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function qc(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new ai(`${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 ai(`${t} requires a value`);return e.splice(n,2),r}function SN(e){if(e.length>0)throw new ai(`Unexpected argument: ${e[0]}`)}async function kN(e){return e?Bj.resolve(e):Lu(process.cwd())}async function EN(e){let t=await qe(e);return _t(e,t?.native.artifact_root??"docs")}function RN(e,t,i){return{command:e,exitCode:0,data:t,text:i??JSON.stringify(t,null,2)+`
|
|
203
203
|
`}}function PN(e,t){if(t instanceof ai)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof xc)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Ja)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof ka)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 Qn)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 Ji)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 CN(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}})+`
|
|
204
|
-
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function AN(e,t){let i=Lc(e,"--repair"),n=qc(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new ai("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();SN(e);let a=await EN(t),o=await bN({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?RN("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}function
|
|
205
|
-
`}}async function xN(e,t,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{Lc(r,"--json"),s=qc(r,"--project-root");let u=[...r,...a],d=await kN(s);c=await t(u,d)}catch(u){c=PN(e,u)}let l=o?
|
|
204
|
+
`}:e.error?{exitCode:e.exitCode,stderr:e.error.message}:{exitCode:e.exitCode,stdout:e.text}}async function AN(e,t){let i=Lc(e,"--repair"),n=qc(e,"--strategy");if(n!==void 0&&n!=="continue"&&n!=="rollback")throw new ai("--strategy must be continue or rollback");let r=e[0]?.startsWith("--")?void 0:e.shift();SN(e);let a=await EN(t),o=await bN({paths:a,...r?{name:r}:{},repair:i,...n?{recoveryStrategy:n}:{}});return o.healthy?RN("doctor",o):{command:"doctor",exitCode:65,data:o,error:{code:"invalid-data",message:"Native project needs attention"}}}function Vj(e){return{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}})+`
|
|
205
|
+
`}}async function xN(e,t,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{Lc(r,"--json"),s=qc(r,"--project-root");let u=[...r,...a],d=await kN(s);c=await t(u,d)}catch(u){c=PN(e,u)}let l=o?Vj(c):CN(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
206
206
|
`)?"":`
|
|
207
207
|
`)),l.exitCode}process.exitCode=await xN("doctor",AN);
|