@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,41 +139,41 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
140
|
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Mr(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(r&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||i.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):r||i.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(i.explicitKey)if(i.sep)if(i.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(yt(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(ud(i.key)&&!yt(i.sep,"newline")){let o=oi(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(yt(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=oi(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):yt(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||i.value?(e.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!yt(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let i=e.items[e.items.length-1];switch(this.type){case"newline":if(i.value){let n="end"in i.value?i.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Mr(r,i.start),r.push(this.sourceToken),e.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=e.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;i.value||yt(i.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let i=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?e.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?e.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!i||i.value?e.items.push({start:[],key:r,sep:[]}):i.sep?this.stack.push(r):Object.assign(i,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let r=Hr(n),a=oi(r);ld(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Hr(e),n=oi(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=Hr(e),n=oi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fd.Parser=Ts});var vd=C(en=>{"use strict";var dd=gs(),Iy=Wi(),Zi=Gi(),_y=mo(),Oy=M(),jy=xs(),hd=Is();function pd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new jy.LineCounter||null,prettyErrors:e}}function $y(t,e={}){let{lineCounter:i,prettyErrors:n}=pd(e),r=new hd.Parser(i?.addNewLine),a=new dd.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(Zi.prettifyError(t,i)),s.warnings.forEach(Zi.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function md(t,e={}){let{lineCounter:i,prettyErrors:n}=pd(e),r=new hd.Parser(i?.addNewLine),a=new dd.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Zi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Zi.prettifyError(t,i)),o.warnings.forEach(Zi.prettifyError(t,i))),o}function Hy(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=md(t,i);if(!r)return null;if(r.warnings.forEach(a=>_y.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 My(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Oy.isDocument(t)&&!n?t.toString(i):new Iy.Document(t,n,i).toString(i)}en.parse=Hy;en.parseAllDocuments=$y;en.parseDocument=md;en.stringify=My});var Os=C(z=>{"use strict";var Ly=gs(),Dy=Wi(),Fy=Xo(),_s=Gi(),By=xi(),Nt=M(),qy=mt(),Vy=Q(),zy=gt(),Wy=wt(),Jy=jr(),Ky=Ps(),Gy=xs(),Uy=Is(),Lr=vd(),gd=Ri();z.Composer=Ly.Composer;z.Document=Dy.Document;z.Schema=Fy.Schema;z.YAMLError=_s.YAMLError;z.YAMLParseError=_s.YAMLParseError;z.YAMLWarning=_s.YAMLWarning;z.Alias=By.Alias;z.isAlias=Nt.isAlias;z.isCollection=Nt.isCollection;z.isDocument=Nt.isDocument;z.isMap=Nt.isMap;z.isNode=Nt.isNode;z.isPair=Nt.isPair;z.isScalar=Nt.isScalar;z.isSeq=Nt.isSeq;z.Pair=qy.Pair;z.Scalar=Vy.Scalar;z.YAMLMap=zy.YAMLMap;z.YAMLSeq=Wy.YAMLSeq;z.CST=Jy;z.Lexer=Ky.Lexer;z.LineCounter=Gy.LineCounter;z.Parser=Uy.Parser;z.parse=Lr.parse;z.parseAllDocuments=Lr.parseAllDocuments;z.parseDocument=Lr.parseDocument;z.stringify=Lr.stringify;z.visit=gd.visit;z.visitAsync=gd.visitAsync});import{execFile as JE,spawn as yl}from"node:child_process";import{createHash as KE}from"node:crypto";import{existsSync as im}from"node:fs";import Ye from"node:path";import{promisify as GE}from"node:util";import{spawn as Nm}from"node:child_process";import Xa from"node:path";var bm=1e3,Sm=2;async function Al(t){let e=t.pid;if(e===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Xa.win32.isAbsolute(i)?Xa.win32.resolve(i):"C:\\Windows",r=Xa.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=Nm(r,["/pid",String(e),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),bm)}catch{u(!1)}});for(let o=0;o<Sm;o+=1)if(await a()){t.kill("SIGKILL");return}t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy();return}try{process.kill(-e,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}t.kill("SIGKILL")}var wa=Pl(Os(),1);import{promises as Th}from"fs";import nt from"path";import{createHash as Zy}from"node:crypto";import{promises as Te}from"node:fs";import Se from"node:path";import{TextDecoder as eN}from"node:util";import js from"path";var Yy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Xy=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Qy(t){return t.toLowerCase().startsWith(".env")}function We(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Qy(n))?"environment-file":i.some(n=>Xy.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Yy.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function wd(t,e){let i=We(e);if(i)return i;let n=js.resolve(t.projectRoot,...e.split("/")),r=js.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===js.resolve(t.configFile)?"native-runtime":null}function bt(t){return t!==0&&t!==0n&&t!=="0"}function se(t,e){return bt(t.dev)&&bt(e.dev)&&bt(t.ino)&&bt(e.ino)}function F(t,e){let i=bt(t.dev)&&bt(e.dev);if(i&&t.dev!==e.dev)return!1;let n=bt(t.ino)&&bt(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Fr=1024*1024;function $s(t,e){let i=Se.relative(t,e);return i===""||!Se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Se.sep}`)}function tN(t){let e=Se.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Se.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=We(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function iN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function nN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Dr(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function yd(t){let e=await Te.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await Te.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function rN(t,e){let i=Se.resolve(t),n=Se.resolve(e);if(!$s(i,n))throw new Error("Native artifact path is outside its root");let r=[await yd(i)],a=i;for(let o of Se.relative(i,n).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s=await yd(a);if(!$s(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Nd(t){for(let e of t){let i=await Te.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!nN(e,i)||await Te.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Ie(t){let e=tN(t.ref),i=iN(t.maxBytes??Fr),n=Se.resolve(t.root,...e.split("/")),r=await rN(t.root,Se.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await Te.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await Te.realpath(n);if(!$s(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await Te.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await Nd(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Dr(a,c)||!Dr(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-d,N=await s.read(p,0,Math.min(p.length,k),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);f.push(Buffer.from(p.subarray(0,N.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await Nd(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Dr(c,m)||!Dr(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(f,d),E;try{E=new eN("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:Zy("sha256").update(w).digest("hex"),text:E}}finally{await s.close()}}import{randomUUID as aN}from"crypto";import{promises as re}from"fs";import _e from"path";function Ms(t,e){let i=_e.relative(t,e);return i===""||!_e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_e.sep}`)}function oN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hs(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function bd(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function tn(t){for(let e of t){let i=await re.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!oN(e,i)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function sN(t,e){let i=_e.resolve(t),n=_e.resolve(e);if(!Ms(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let r=[await bd(i)],a=_e.relative(i,n).split(_e.sep).filter(Boolean),o=i;for(let s of a){await tn(r),o=_e.join(o,s);try{await re.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await bd(o);if(!Ms(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await tn(r),r}async function cN(t){let e;try{e=await re.open(t,"r"),await e.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await e?.close()}}async function lN(t,e,i={}){let n=_e.dirname(t),r=i.containedRoot?await sN(i.containedRoot,n):null;r||await re.mkdir(n,{recursive:!0});let a=_e.join(n,`.${_e.basename(t)}.${aN()}.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 tn(r),!c.isFile()||c.isSymbolicLink()||!Hs(s,c)||!Ms(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Hs(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 tn(r);let c=await re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Hs(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await re.link(a,t),await re.unlink(a)):await re.rename(a,t),await cN(n)}catch(c){if(await o?.close(),!r)await re.rm(a,{force:!0});else try{await tn(r),await re.rm(a,{force:!0})}catch{}throw c}}async function Ze(t,e,i={}){await lN(t,e,i)}async function Oe(t,e,i={}){await Ze(t,JSON.stringify(e,null,2)+`
|
|
143
|
-
`,i)}var Ds=Pl(Os(),1);import Br from"path";var zr=64*1024,qr=1024,Vr=64,Fs=5,uN=[".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/**"],de={include:["**/*"],exclude:[...uN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function fN(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Br.posix.isAbsolute(i)||Br.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function Ft(t){let e=fN(t,"native.artifact_root");return e.length===0?".":e.join("/")}function kd(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Bs(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Br.posix.isAbsolute(n)||Br.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function nn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ed(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Wr(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>qr)throw new Error(`${e} exceeds ${qr} characters`);let i=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?i+=1:t[n]==="*"&&(i+=1,t[n+1]==="*"&&(n+=1));if(i>Vr)throw new Error(`${e} contains more than ${Vr} wildcard tokens`);return t}function Sd(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>Wr(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function Ls(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function dN(t){if(t===void 0)return{...de,include:[...de.include],exclude:[...de.exclude]};let e=nn(t,"native.snapshot");return{include:Sd(e.include,"native.snapshot.include",de.include),exclude:Sd(e.exclude,"native.snapshot.exclude",de.exclude),max_files:Ls(e.max_files,de.max_files,"native.snapshot.max_files"),max_total_bytes:Ls(e.max_total_bytes,de.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ls(e.max_duration_ms,de.max_duration_ms,"native.snapshot.max_duration_ms")}}function hN(t){if(t===void 0)return;let e=nn(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=nn(e.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:Ft(n),toArtifactRoot:Ft(r),stage:a,...o?{cleanup:o}:{}}}function pN(t){let e=nn(t,"native");if(typeof e.artifact_root!="string")throw new Error("native.artifact_root must be a string");let i=e.clarification_mode??"sequential";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let n=e.archive_confirmation??"automatic";if(n!=="automatic"&&n!=="required")throw new Error("native.archive_confirmation must be automatic or required");let r=e.max_verify_failures??Fs;if(!Number.isSafeInteger(r)||r<1)throw new Error("native.max_verify_failures must be a positive integer");let a=hN(e.pending_root_move);return{artifact_root:Ft(e.artifact_root),language:Ed(e.language,"en","native.language"),clarification_mode:i,archive_confirmation:n,max_verify_failures:r,snapshot:dN(e.snapshot),...a?{pending_root_move:a}:{}}}function mN(t){let e=nn(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:kd(e.artifact_layout),language:Ed(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function vN(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function gN(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function Jr(t,e={}){let i=(0,Ds.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=vN(r.ambient_resume),o=r.native===void 0?void 0:pN(r.native),s=r.classic===void 0?void 0:mN(r.classic),c=gN(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function qs(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Ft(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Fs,snapshot:{...de,include:[...de.include],exclude:[...de.exclude]}}}}import{createHash as yN}from"crypto";import{promises as Ur}from"fs";import St from"path";import{constants as Kr,promises as Bt}from"fs";var je=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function Vs(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Rd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function rn(t){return{dev:t.dev,ino:t.ino,birthtime:Vs(t)}}function Gr(t,e){let i=rn(t),n=rn(e);return se(i,n)?F(i,n):F(i,n)&&Vs(t)===Vs(e)&&Rd(t)===Rd(e)&&t.size===e.size}async function si(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Bt.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new je("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new je("too-large",`${n} exceeds ${e} bytes`);let o=await Bt.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:rn(a)});let s=process.platform==="win32"?Kr.O_RDONLY:Kr.O_RDONLY|Kr.O_NOFOLLOW|Kr.O_NONBLOCK,c;try{c=await Bt.open(t,s)}catch(l){throw l.code==="ELOOP"?new je("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),Bt.lstat(t,{bigint:r}),Bt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Gr(a,l)||!Gr(a,u))throw new je("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:rn(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let E=e+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,E),null);if(k===0)break;if(p+=k,p>e)throw new je("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:r}),Bt.lstat(t,{bigint:r}),Bt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!Gr(a,h)||!Gr(a,v))throw new je("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:rn(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:w}}finally{await c.close()}}function wN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function zs(t,e){let i=St.relative(t,e);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}async function Cd(t,e){let i=St.resolve(t),n=await Ur.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Ur.realpath(i)}async function Pd(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=St.join(r,i[a]);let o;try{o=await Ur.lstat(r)}catch(u){if(wN(u))return{exists:!1,kind:"missing"};throw u}let s=St.relative(t,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await Ur.realpath(r);if(!zs(e,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function an(t,e,i){let n=Bs(e,i.label),r=St.resolve(t),a=await Cd(r,i.label),o=n.split("/"),s=St.resolve(r,...o);if(!zs(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Pd(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ci(t,e,i,n){let r=await an(t,e,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await Cd(r.projectRoot,n.label);return si(r.target,i,{...n,verify:async(o,s)=>{if(!zs(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Pd(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var on=".comet/config.yaml";function NN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ws(t,e={}){return(await Yr(t,e)).document}async function bN(t){try{return(await ci(t,on,zr,{label:on})).bytes}catch(e){if(NN(e))return null;throw e}}function SN(t){return t?{exists:!0,sha256:yN("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Yr(t,e={}){let i=await bN(t);return{document:i?Jr(i.toString("utf8"),e):null,identity:SN(i)}}var OP=16*1024;import{promises as li}from"fs";import K from"path";import CN from"os";var Xr=".comet/config.yaml";async function Ks(t){try{return await li.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function PN(t){try{let e=await li.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function sn(t,e){let i=K.relative(t,e);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function cn(t){let e=[],i=t;for(;!await Ks(i);){let r=K.dirname(i);if(r===i)break;e.push(K.basename(i)),i=r}let n=await li.realpath(i);return K.resolve(n,...e.reverse())}async function Id(t){try{return(await li.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Qr(t){let e=K.resolve(t);try{(await li.stat(e)).isDirectory()||(e=K.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=K.resolve(CN.homedir());for(;;){if(!(e===n&&i!==n)){let o=K.join(e,...Xr.split("/")),s=e===i||await PN(o);if(await Ks(o)&&s)return e}if(await Ks(K.join(e,".git")))return e;let a=K.dirname(e);if(a===e)return i;e=a}}function Zr(t){return Ft(t)}async function AN(t,e){let i=Zr(e),n=K.resolve(t,...i.split("/")),r=await li.realpath(t),a=await cn(n);if(!sn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Gs(t,e){let i=Zr(e),n=await AN(t,i),r=K.join(n,"comet");if(await Id(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([cn(n),cn(r)]);if(!sn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:K.resolve(t),configFile:K.join(t,...Xr.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:K.join(r,"specs"),changesDir:K.join(r,"changes"),archiveDir:K.join(r,"archive"),runtimeDir:K.join(r,"runtime"),locksDir:K.join(r,"runtime","locks"),transactionsDir:K.join(r,"runtime","transactions")}}function ae(t,e){return sn(K.resolve(t),K.resolve(e))}async function q(t,e){let i=K.resolve(t),n=K.resolve(e);if(!sn(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Id(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([cn(i),cn(n)]);if(!sn(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var Us=de;var ea=Wr;function TN(t="docs",e="en"){return qs(t,e)}async function qt(t){let e=(await Ws(t))?.config??null;return e?.native?e:null}async function ln(t){let e=await qt(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function _d(t){let e=await Qr(t.startPath),i=await qt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Xr} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=t.explicitArtifactRoot?Zr(t.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??TN(n??"docs"),a=await Gs(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as ob}from"fs";import sb from"path";import{AsyncLocalStorage as IN}from"async_hooks";import{randomUUID as $d}from"crypto";import{promises as ke}from"fs";import Hd from"os";import ce from"path";var Od=16*1024,Md=".coordinator",_N=5e3,jd=new IN,ta=new Map;function ON(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function jN(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;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: ${e}`);return i}function Ld(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function Ys(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return se(i,n)?F(i,n):F(i,n)&&t.size===e.size}function Xs(t,e){return Ys(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function et(t){let e,i;try{let n=await si(t,Od,{bigint:!0,label:"Native lock"});e=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof je?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Od} bytes: ${t}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:n}):new Error(`Native lock changed while reading: ${t}`,{cause:n}):n}return{file:t,owner:jN(JSON.parse(e.toString("utf8")),t),identity:Ld(i)}}async function $N(t){return(await et(t))?.owner??null}function Dd(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Hd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=BN(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function HN(t,e){try{await ke.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ke.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Qs(t,e){let i=await et(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Xs(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await ke.mkdir(e,{recursive:!0});let n=ce.join(e,`${ce.basename(t.file)}.${t.owner.id}.${$d()}.removed`);try{await ke.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await et(n);if(!r||r.owner.id!==t.owner.id||!Ys(r.identity,t.identity))throw await HN(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await ke.rm(n,{force:!0}),"removed"}function Fd(t){return{id:$d(),pid:process.pid,hostname:Hd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Bd(t,e){let i;try{i=await ke.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let r=await $N(t);throw new Error(`Native lock is already held: ${t}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
144
|
-
`,"utf8"),await i.sync(),Ld(await i.stat({bigint:!0}))}finally{await i.close()}}async function MN(t,e){let i=await q(t.nativeRoot,t.locksDir);await ke.mkdir(i,{recursive:!0});let n=await q(t.nativeRoot,ce.join(i,Md));await ke.mkdir(n,{recursive:!0});let r=Fd(e),a=ce.join(n,`.${r.id}.tmp`),o=ce.join(n,`${r.id}.claim`);try{let s=await Bd(a,r);await ke.rename(a,o);let c=await et(o);if(!c||!Ys(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await ke.rm(a,{force:!0})}}async function LN(t){let e=ce.dirname(t.file),i=!1,n=ce.basename(t.file);for(let r of await ke.readdir(e,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ce.join(e,r.name);if(ce.resolve(a)!==ce.resolve(t.file))try{let o=await et(a),s=Dd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Qs(o,e);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function qd(t){let e=await et(t.file);if(e){if(e.owner.id!==t.owner.id||!Xs(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Qs(e,ce.dirname(t.file))}}async function DN(t,e){let i=Date.now()+_N;for(;;){let n=await MN(t,e);if(!await LN(n))return n;if(await qd(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function FN(t){let e=ta.get(t)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=e.then(()=>n);return ta.set(t,r),await e,()=>{i(),ta.get(t)===r&&ta.delete(t)}}async function Vd(t,e,i){let n=ce.resolve(t.locksDir),r=jd.getStore();if(r?.has(n))return i();let a=await FN(n);try{let o=await DN(t,e),s=new Map(r??[]);return s.set(n,o),await jd.run(s,async()=>{try{return await i()}finally{await qd(o)}})}finally{a()}}async function un(t,e,i){return Vd(t,`acquire ${e}`,async()=>{let n=await q(t.nativeRoot,t.locksDir);await ke.mkdir(n,{recursive:!0});let r=await q(t.nativeRoot,ce.join(n,ON(e))),a=Fd(i),o=await Bd(r,a);return{file:r,nativeRoot:t.nativeRoot,locksDir:n,owner:a,identity:o}})}async function fn(t){await et(t.file)&&await Vd(t,`release ${ce.basename(t.file)}`,async()=>{let e=await et(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Xs(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=ce.join(t.locksDir,Md);await Qs(e,i)})}function BN(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function zd(t){return Dd(await et(t))}import it from"path";import{TextDecoder as YN}from"util";import{createHash as qN}from"node:crypto";import{constants as ia,promises as $e}from"node:fs";import He from"node:path";import{TextDecoder as VN}from"node:util";function ra(t,e){let i=He.relative(t,e);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function zN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function WN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function JN(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function na(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Zs(t,e){let i=await $e.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await $e.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function KN(t,e,i){let n=He.resolve(t),r=He.resolve(e);if(!ra(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Zs(n,i)],o=n;for(let s of He.relative(n,r).split(He.sep).filter(Boolean)){await Vt(a,i),o=He.join(o,s);let c=await Zs(o,i);if(!ra(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Vt(a,i),a}async function Vt(t,e){for(let i of t){let n=await $e.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!WN(i,n)||await $e.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function GN(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function tt(t){let e=zN(t.maxBytes),i=He.resolve(t.file),n=await KN(t.root,He.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(u=>Zs(He.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Vt(n,t.label);let a=await $e.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=JN(a),s=await $e.realpath(i);if(!ra(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(u=>ra(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ia.O_RDONLY:ia.O_RDONLY|ia.O_NOFOLLOW|ia.O_NONBLOCK,l=await $e.open(i,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([$e.lstat(i),$e.realpath(i)]);if(await Vt(n,t.label),await Vt(r,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!na(o,u)||!na(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await GN(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),$e.lstat(i),$e.realpath(i)]);if(await Vt(n,t.label),await Vt(r,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!na(o,m)||!na(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:qN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Wd(t){let e=await tt(t),i;try{i=new VN("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}var XN=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),QN=new Set(["id","type","source","target","staged","backup"]),ZN=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),eb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Gd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var tb=256*1024,kA=1024*1024,EA=16*1024;var RA=64*1024*1024;var ib=new YN("utf-8",{fatal:!0});function oa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function sa(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Ud(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function ec(t,e){if(typeof t!="string"||t.length===0||it.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function aa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Jd(t,e){if(ec(t,e),t.includes("\\")||t!==it.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function nb(t,e){let i=oa(t,`transaction operations[${e}]`);if(sa(i,QN,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);ec(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&ec(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 Yd(t){let e=oa(t,"Native Archive transaction journal");if(sa(e,ZN,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Gd.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Ud(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(aa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=oa(s,`Archive transaction operations[${c}]`);if(sa(l,eb,`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`);Jd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Jd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&aa(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(aa(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`);aa(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/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function rb(t){let e=oa(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Yd(e);if(sa(e,XN,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Gd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!it.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!it.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Ud(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(nb),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:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function ab(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return it.join(t.transactionsDir,e)}function Xd(t,e){let i=ab(t,e);return{directory:i,journal:it.join(i,"transaction.json"),events:it.join(i,"events.jsonl"),staged:it.join(i,"staged"),backups:it.join(i,"backups")}}async function ic(t,e){let i=Xd(t,e);return await Promise.all(Object.values(i).map(n=>q(t.nativeRoot,n))),i}async function nc(t,e,i={}){let n=await ic(t,e),r=await tt({root:t.nativeRoot,file:n.journal,maxBytes:tb,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(ib.decode(r.bytes)),o=rb(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function cb(t,e){let i;try{i=await ob.readdir(t.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 nc(t,n.name);if(r.id!==e&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function lb(t,e){let i=Date.now()+5e3,n=sb.join(t.locksDir,"root-move.lock");for(;;)try{return await un(t,"root-move",e)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await zd(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 kt(t,e,i,n){let r=await lb(t,e);try{if(await ln(t.projectRoot),await cb(t,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fn(r)}}function Qd(t){return Number.isSafeInteger(t)&&t>=1}async function Zd(t){if(!Qd(t.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(t.next.revision!==t.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let e=await t.read();if(!Qd(e.revision))throw new Error("Native current revision must be a positive integer");let i=t.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(e.revision===t.next.revision&&i(e,t.next))return e;if(e.revision!==t.expectedRevision)throw t.conflict(e.revision);return await t.write(t.next),t.next}import{createHash as fa}from"crypto";import{spawn as uh}from"node:child_process";import{promises as U}from"fs";import V from"path";import{createHash as ub}from"crypto";function G(t){return ub("sha256").update(t).digest("hex")}var ca={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},fh=1e3,fb=8*1024*1024,db=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),pb=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),mb=new Set(["schema","include","exclude","hash"]),vb=new Set(["provider","gitSelection","physicalSelection","projection"]),gb=new Set(["provider","selection"]),wb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),yb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Nb=new Set(["schema","status","before","after"]),bb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Sb=new Set(["path","hash","size","type","gitObjectId"]),kb=new Set(["path","size","type","reason"]),Eb=new Set(["ref","hash","count"]),Rb=new Set(["change-created","legacy-migration","explicit"]),Cb=new Set(["file","directory","other"]),Pb=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"]),da=/^[a-f0-9]{64}$/u,dh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Ab=new Set(["EACCES","EPERM"]),di=64*1024,lc=64*1024,xb=6e4,Tb=1e3,Ib=2,hh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},_b={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function Ob(t){let e=t.deadlineMs??xb;if(!Number.isSafeInteger(e)||e<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+e,gitProcess:t.gitProcess??{command:"git"}}}function Me(t){return Math.max(0,t.deadlineAt-Date.now())}function _(t){return Me(t)>=1}function rc(t){let e=t===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:t});return Object.assign(e,{code:"GIT_SNAPSHOT_TIMEOUT"})}function dn(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function jb(t){let e={..._b,...t};if(!Number.isSafeInteger(e.maxNodes)||e.maxNodes<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxPathBytes)||e.maxPathBytes<1||e.maxPathBytes>e.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return e}async function $b(t,e){if(e.terminateTree){await e.terminateTree(t);return}let i=t.pid;if(i===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&V.win32.isAbsolute(n)?V.win32.resolve(n):"C:\\Windows",a=V.win32.join(r,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.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,f=(d,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(d))};try{l=uh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>f(!1)),l.once("close",d=>f(d===0)),u=setTimeout(()=>f(!1,!0),Tb),u.unref()}catch{f(!1)}});for(let s=0;s<Ib;s+=1)if(await o()){t.kill("SIGKILL");return}throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.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}t.kill("SIGKILL")}function fc(t,e,i,n){let r=Me(t);if(r<1)throw rc();let a=t.gitProcess,o=uh(a.command,[...a.argsPrefix??[],"-C",e,...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)}),f=setTimeout(()=>{c=!0,l=$b(o,a).then(()=>({error:null}),p=>({error:p}))},r);f.unref();let d=u.then(async p=>{if(clearTimeout(f),c){let m=await l;throw m?.error?rc(m.error):rc()}return{code:p,spawnError:s}});return{child:o,completion:d}}function Hb(t){let e={...hh,...t};if(!Number.isSafeInteger(e.maxRecords)||e.maxRecords<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxRecordBytes)||e.maxRecordBytes<1||e.maxRecordBytes>e.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return e}async function la(t,e,i,n=lc){let{child:r,completion:a}=fc(t,e,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>=di)return;let m=di-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:f,spawnError:d}=await a;if(f===0&&d===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${d?`: ${d.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function ac(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function oc(t,e,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}=fc(t,e,i,n.stdin!==void 0),c=[],l=fa("sha256"),u=[],f=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,w=!1,E=!1,k=N=>{let S=0;for(;S<N.byteLength;){let g=N.indexOf(0,S),b=g<0?N.byteLength:g,y=N.subarray(S,b);if(!v&&y.byteLength>0&&(h.byteLength+y.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,w=!0):h=Buffer.concat([h,y])),g<0)break;m+=1,h.byteLength===0&&!v&&(E=!0);let R=h.byteLength+1;!v&&m<=n.maxRecords&&p+R<=n.maxBytes?(c.push(h),p+=R):w=!0,h=Buffer.alloc(0),v=!1,S=g+1}};o.stdout.on("data",N=>{l.update(N),d+=N.byteLength,d>n.maxBytes&&(w=!0);let S=n.outputChunkBytes;if(S===void 0){k(N);return}for(let g=0;g<N.byteLength;g+=S)k(N.subarray(g,Math.min(N.byteLength,g+S)))}),o.stderr.on("data",N=>{if(f>=di)return;let S=di-f,g=Buffer.from(N).subarray(0,S);u.push(g),f+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:S})=>{let g=n.acceptedExitCodes??[0];if(N!==null&&g.includes(N)&&S===null&&!E&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:w,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${S?`: ${S.message}`:E||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function eh(t){let e=t.toString("utf8");if(!Buffer.from(e,"utf8").equals(t))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return e}async function Mb(t,e,i){let{child:n,completion:r}=fc(t,e,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=di)return;let f=di-o,d=Buffer.from(u).subarray(0,f);a.push(d),o+=d.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 ua(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||V.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||V.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function Lb(t,e){return t.map(i=>{let n=ua(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return n})}async function Db(t){let e=V.resolve(t);for(;;){try{return await U.lstat(V.join(e,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=V.dirname(e);if(i===e)return!1;e=i}}async function ph(t,e,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await oc(t,e,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await oc(t,e,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await oc(t,e,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function mh(t){return{stageBefore:ac(t.stagedBefore),combined:ac(t.combined),stageAfter:ac(t.stagedAfter)}}async function Fb(t,e,i=hh,n={}){if(!await Db(e))return null;let r;try{r=await la(t,e,["rev-parse","--is-inside-work-tree"])}catch(w){throw dn(w)?w:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:w})}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 ph(t,e,i,n)}catch(w){throw dn(w)?w:new Error("Native Git snapshot provider failed after repository detection",{cause:w})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,f=new Set,d=w=>{for(let E of w){let k=eh(E),N=k.indexOf(" ");if(N<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,N))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let g=ua(k.slice(N+1));if(g===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(g),S.stage==="0"&&u.set(g,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(g)}};d(o.records),d(c.records);let p=s.records.map(eh),m=Lb(p,"combined"),h=new Set(m.filter(w=>!l.has(w))),v=new Set(m.filter((w,E)=>!l.has(w)&&p[E].endsWith("/")));for(let w of f)v.delete(w);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:f,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:mh(a)}}function Rt(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function th(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function Bb(t,e){return!Rt(t.stageBefore,t.stageAfter)||!Rt(t.stageAfter,e.stageBefore)||!Rt(t.combined,e.combined)||!Rt(e.stageBefore,e.stageAfter)}async function qb(t,e,i,n,r){let a;try{a=await ph(t,e,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw dn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=mh(a),c=th(o)||th(s),l=Bb(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:G(`comet.native.git-selection-overflow.v2
|
|
145
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
142
|
+
`,i)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let i=Hr(e),n=oi(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=Hr(e),n=oi(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,i){return this.type!=="comment"||this.indent<=i?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fd.Parser=Ts});var vd=C(en=>{"use strict";var dd=gs(),Iy=Wi(),Zi=Gi(),_y=mo(),Oy=M(),jy=xs(),hd=Is();function pd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new jy.LineCounter||null,prettyErrors:e}}function $y(t,e={}){let{lineCounter:i,prettyErrors:n}=pd(e),r=new hd.Parser(i?.addNewLine),a=new dd.Composer(e),o=Array.from(a.compose(r.parse(t)));if(n&&i)for(let s of o)s.errors.forEach(Zi.prettifyError(t,i)),s.warnings.forEach(Zi.prettifyError(t,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function md(t,e={}){let{lineCounter:i,prettyErrors:n}=pd(e),r=new hd.Parser(i?.addNewLine),a=new dd.Composer(e),o=null;for(let s of a.compose(r.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Zi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&i&&(o.errors.forEach(Zi.prettifyError(t,i)),o.warnings.forEach(Zi.prettifyError(t,i))),o}function Hy(t,e,i){let n;typeof e=="function"?n=e:i===void 0&&e&&typeof e=="object"&&(i=e);let r=md(t,i);if(!r)return null;if(r.warnings.forEach(a=>_y.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 My(t,e,i){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:i===void 0&&e&&(i=e),typeof i=="string"&&(i=i.length),typeof i=="number"){let r=Math.round(i);i=r<1?void 0:r>8?{indent:8}:{indent:r}}if(t===void 0){let{keepUndefined:r}=i??e??{};if(!r)return}return Oy.isDocument(t)&&!n?t.toString(i):new Iy.Document(t,n,i).toString(i)}en.parse=Hy;en.parseAllDocuments=$y;en.parseDocument=md;en.stringify=My});var Os=C(z=>{"use strict";var Ly=gs(),Dy=Wi(),Fy=Xo(),_s=Gi(),By=xi(),Nt=M(),qy=mt(),Vy=Q(),zy=gt(),Wy=wt(),Jy=jr(),Ky=Ps(),Gy=xs(),Uy=Is(),Lr=vd(),gd=Ri();z.Composer=Ly.Composer;z.Document=Dy.Document;z.Schema=Fy.Schema;z.YAMLError=_s.YAMLError;z.YAMLParseError=_s.YAMLParseError;z.YAMLWarning=_s.YAMLWarning;z.Alias=By.Alias;z.isAlias=Nt.isAlias;z.isCollection=Nt.isCollection;z.isDocument=Nt.isDocument;z.isMap=Nt.isMap;z.isNode=Nt.isNode;z.isPair=Nt.isPair;z.isScalar=Nt.isScalar;z.isSeq=Nt.isSeq;z.Pair=qy.Pair;z.Scalar=Vy.Scalar;z.YAMLMap=zy.YAMLMap;z.YAMLSeq=Wy.YAMLSeq;z.CST=Jy;z.Lexer=Ky.Lexer;z.LineCounter=Gy.LineCounter;z.Parser=Uy.Parser;z.parse=Lr.parse;z.parseAllDocuments=Lr.parseAllDocuments;z.parseDocument=Lr.parseDocument;z.stringify=Lr.stringify;z.visit=gd.visit;z.visitAsync=gd.visitAsync});import{execFile as KE,spawn as yl}from"node:child_process";import{createHash as GE}from"node:crypto";import{existsSync as im}from"node:fs";import Ye from"node:path";import{promisify as UE}from"node:util";import{spawn as Nm}from"node:child_process";import Xa from"node:path";var bm=1e3,Sm=2;async function Al(t){let e=t.pid;if(e===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Xa.win32.isAbsolute(i)?Xa.win32.resolve(i):"C:\\Windows",r=Xa.win32.join(n,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=Nm(r,["/pid",String(e),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),bm)}catch{u(!1)}});for(let o=0;o<Sm;o+=1)if(await a()){t.kill("SIGKILL");return}t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy();return}try{process.kill(-e,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}t.kill("SIGKILL")}var wa=Pl(Os(),1);import{promises as Th}from"fs";import nt from"path";import{createHash as Zy}from"node:crypto";import{promises as Te}from"node:fs";import Se from"node:path";import{TextDecoder as eN}from"node:util";import js from"path";var Yy=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Xy=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Qy(t){return t.toLowerCase().startsWith(".env")}function We(t){let i=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return i.some(n=>Qy(n))?"environment-file":i.some(n=>Xy.has(n))?"credential-config":i.includes(".git")?"git-metadata":i.some(n=>Yy.has(n))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function wd(t,e){let i=We(e);if(i)return i;let n=js.resolve(t.projectRoot,...e.split("/")),r=js.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),a=e.replaceAll("\\","/");return a===r||a.startsWith(`${r}/`)||n===js.resolve(t.configFile)?"native-runtime":null}function bt(t){return t!==0&&t!==0n&&t!=="0"}function se(t,e){return bt(t.dev)&&bt(e.dev)&&bt(t.ino)&&bt(e.ino)}function F(t,e){let i=bt(t.dev)&&bt(e.dev);if(i&&t.dev!==e.dev)return!1;let n=bt(t.ino)&&bt(e.ino);return n&&t.ino!==e.ino?!1:i&&n?!0:t.birthtime===e.birthtime}var Fr=1024*1024;function $s(t,e){let i=Se.relative(t,e);return i===""||!Se.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Se.sep}`)}function tN(t){let e=Se.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(r=>{let a=r.codePointAt(0)??0;return a<=31||a===127})||Se.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let i=t.toLowerCase(),n=We(t);if(n||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function iN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function nN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Dr(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function yd(t){let e=await Te.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await Te.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function rN(t,e){let i=Se.resolve(t),n=Se.resolve(e);if(!$s(i,n))throw new Error("Native artifact path is outside its root");let r=[await yd(i)],a=i;for(let o of Se.relative(i,n).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s=await yd(a);if(!$s(r[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);r.push(s)}return r}async function Nd(t){for(let e of t){let i=await Te.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!nN(e,i)||await Te.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function Ie(t){let e=tN(t.ref),i=iN(t.maxBytes??Fr),n=Se.resolve(t.root,...e.split("/")),r=await rN(t.root,Se.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await Te.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);let o=await Te.realpath(n);if(!$s(r[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await Te.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await Nd(r),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Dr(a,c)||!Dr(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(Math.min(64*1024,i+1));for(;;){let k=i+1-d,N=await s.read(p,0,Math.min(p.length,k),null);if(N.bytesRead===0)break;if(d+=N.bytesRead,d>i)throw new Error(`Native artifact exceeds ${i} bytes: ${e}`);f.push(Buffer.from(p.subarray(0,N.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),Te.lstat(n),Te.realpath(n)]);if(await Nd(r),!h.isFile()||h.isSymbolicLink()||v!==o||!Dr(c,m)||!Dr(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(f,d),E;try{E=new eN("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:Zy("sha256").update(w).digest("hex"),text:E}}finally{await s.close()}}import{randomUUID as aN}from"crypto";import{promises as re}from"fs";import _e from"path";function Ms(t,e){let i=_e.relative(t,e);return i===""||!_e.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${_e.sep}`)}function oN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Hs(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function bd(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function tn(t){for(let e of t){let i=await re.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!oN(e,i)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function sN(t,e){let i=_e.resolve(t),n=_e.resolve(e);if(!Ms(i,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let r=[await bd(i)],a=_e.relative(i,n).split(_e.sep).filter(Boolean),o=i;for(let s of a){await tn(r),o=_e.join(o,s);try{await re.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await bd(o);if(!Ms(r[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await tn(r),r}async function cN(t){let e;try{e=await re.open(t,"r"),await e.sync()}catch(i){let n=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw i}finally{await e?.close()}}async function lN(t,e,i={}){let n=_e.dirname(t),r=i.containedRoot?await sN(i.containedRoot,n):null;r||await re.mkdir(n,{recursive:!0});let a=_e.join(n,`.${_e.basename(t)}.${aN()}.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 tn(r),!c.isFile()||c.isSymbolicLink()||!Hs(s,c)||!Ms(r[0].realPath,l))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),!Hs(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 tn(r);let c=await re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!Hs(c,s))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await re.link(a,t),await re.unlink(a)):await re.rename(a,t),await cN(n)}catch(c){if(await o?.close(),!r)await re.rm(a,{force:!0});else try{await tn(r),await re.rm(a,{force:!0})}catch{}throw c}}async function Ze(t,e,i={}){await lN(t,e,i)}async function Oe(t,e,i={}){await Ze(t,JSON.stringify(e,null,2)+`
|
|
143
|
+
`,i)}var Ds=Pl(Os(),1);import Br from"path";var zr=64*1024,qr=1024,Vr=64,Fs=5,uN=[".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/**"],de={include:["**/*"],exclude:[...uN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4};function fN(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim();if(i.length===0||Br.posix.isAbsolute(i)||Br.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be a project-relative path`);if(i===".")return[];let n=i.replaceAll("\\","/").split("/");if(n.some(r=>r===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(r=>r===""||r==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function Ft(t){let e=fN(t,"native.artifact_root");return e.length===0?".":e.join("/")}function kd(t,e="docs"){let i=t??e;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Bs(t,e,i=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Br.posix.isAbsolute(n)||Br.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let r=n.split("/");if(r.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(r.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return r.join("/")}function nn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ed(t,e,i){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return n}function Wr(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>qr)throw new Error(`${e} exceeds ${qr} characters`);let i=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?i+=1:t[n]==="*"&&(i+=1,t[n+1]==="*"&&(n+=1));if(i>Vr)throw new Error(`${e} contains more than ${Vr} wildcard tokens`);return t}function Sd(t,e,i){if(t===void 0)return[...i];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(n=>Wr(n,e)))].sort((n,r)=>n.localeCompare(r,"en"))}function Ls(t,e,i){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${i} must be a positive integer`);return n}function dN(t){if(t===void 0)return{...de,include:[...de.include],exclude:[...de.exclude]};let e=nn(t,"native.snapshot");return{include:Sd(e.include,"native.snapshot.include",de.include),exclude:Sd(e.exclude,"native.snapshot.exclude",de.exclude),max_files:Ls(e.max_files,de.max_files,"native.snapshot.max_files"),max_total_bytes:Ls(e.max_total_bytes,de.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Ls(e.max_duration_ms,de.max_duration_ms,"native.snapshot.max_duration_ms")}}function hN(t){if(t===void 0)return;let e=nn(t,"native.pending_root_move"),i=e.id,n=e.from_artifact_root,r=e.to_artifact_root,a=e.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof r!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let s=nn(e.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:Ft(n),toArtifactRoot:Ft(r),stage:a,...o?{cleanup:o}:{}}}function pN(t,e={}){let i=nn(t,"native"),n=i.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let r=i.clarification_mode??"sequential";if(r!=="sequential"&&r!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Fs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=hN(i.pending_root_move);return{artifact_root:Ft(n),language:Ed(i.language,"en","native.language"),clarification_mode:r,archive_confirmation:a,max_verify_failures:o,snapshot:dN(i.snapshot),...s?{pending_root_move:s}:{}}}function mN(t){let e=nn(t,"classic"),i=e.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=e.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:kd(e.artifact_layout),language:Ed(e.language,"zh-CN","classic.language"),context_compression:i,review_mode:n,auto_transition:r}}function vN(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function gN(t,e,i,n,r){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!r.allowPartialProject&&t.native!==void 0)||r.allowPartialProject&&!a)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:n,...e?{native:e}:{},...i?{classic:i}:{}}}function Jr(t,e={}){let i=(0,Ds.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let n=i.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=n,a=vN(r.ambient_resume),o=r.native===void 0?void 0:pN(r.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=r.classic===void 0?void 0:mN(r.classic),c=gN(r,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:r,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}function qs(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,native:{artifact_root:Ft(t),language:e,clarification_mode:"sequential",archive_confirmation:"automatic",max_verify_failures:Fs,snapshot:{...de,include:[...de.include],exclude:[...de.exclude]}}}}import{createHash as yN}from"crypto";import{promises as Ur}from"fs";import St from"path";import{constants as Kr,promises as Bt}from"fs";var je=class extends Error{reason;constructor(e,i,n){super(i,n),this.name="RaceSafeReadError",this.reason=e}};function Vs(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Rd(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function rn(t){return{dev:t.dev,ino:t.ino,birthtime:Vs(t)}}function Gr(t,e){let i=rn(t),n=rn(e);return se(i,n)?F(i,n):F(i,n)&&Vs(t)===Vs(e)&&Rd(t)===Rd(e)&&t.size===e.size}async function si(t,e,i={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let n=i.label??"file",r=i.bigint===!0,a=await Bt.lstat(t,{bigint:r});if(!a.isFile()||a.isSymbolicLink())throw new je("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new je("too-large",`${n} exceeds ${e} bytes`);let o=await Bt.realpath(t);await i.verify?.("pre-open",{realPath:o,identity:rn(a)});let s=process.platform==="win32"?Kr.O_RDONLY:Kr.O_RDONLY|Kr.O_NOFOLLOW|Kr.O_NONBLOCK,c;try{c=await Bt.open(t,s)}catch(l){throw l.code==="ELOOP"?new je("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:r}),Bt.lstat(t,{bigint:r}),Bt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Gr(a,l)||!Gr(a,u))throw new je("changed",`${n} changed while opening`);await i.verify?.("post-open",{realPath:f,identity:rn(l)}),await i.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let E=e+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,E),null);if(k===0)break;if(p+=k,p>e)throw new je("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(m.subarray(0,k)))}await i.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:r}),Bt.lstat(t,{bigint:r}),Bt.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!Gr(a,h)||!Gr(a,v))throw new je("changed",`${n} changed while reading`);return await i.verify?.("post-read",{realPath:w,identity:rn(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:w}}finally{await c.close()}}function wN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function zs(t,e){let i=St.relative(t,e);return i===""||!St.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${St.sep}`)}async function Cd(t,e){let i=St.resolve(t),n=await Ur.lstat(i);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return Ur.realpath(i)}async function Pd(t,e,i,n){let r=t;for(let a=0;a<i.length;a++){r=St.join(r,i[a]);let o;try{o=await Ur.lstat(r)}catch(u){if(wN(u))return{exists:!1,kind:"missing"};throw u}let s=St.relative(t,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await Ur.realpath(r);if(!zs(e,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function an(t,e,i){let n=Bs(e,i.label),r=St.resolve(t),a=await Cd(r,i.label),o=n.split("/"),s=St.resolve(r,...o);if(!zs(r,s))throw new Error(`${i.label} must stay inside the project root`);let c=await Pd(r,a,o,i);return{projectRoot:r,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ci(t,e,i,n){let r=await an(t,e,{label:n.label,expected:"file"});if(!r.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await Cd(r.projectRoot,n.label);return si(r.target,i,{...n,verify:async(o,s)=>{if(!zs(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Pd(r.projectRoot,a,r.relative.split("/"),{label:n.label,expected:"file"})}})}var on=".comet/config.yaml";function NN(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Ws(t,e={}){return(await Yr(t,e)).document}async function bN(t){try{return(await ci(t,on,zr,{label:on})).bytes}catch(e){if(NN(e))return null;throw e}}function SN(t){return t?{exists:!0,sha256:yN("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Yr(t,e={}){let i=await bN(t);return{document:i?Jr(i.toString("utf8"),e):null,identity:SN(i)}}var jP=16*1024;import{promises as li}from"fs";import K from"path";import PN from"os";var Xr=".comet/config.yaml";async function Ks(t){try{return await li.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function AN(t){try{let e=await li.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function sn(t,e){let i=K.relative(t,e);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function cn(t){let e=[],i=t;for(;!await Ks(i);){let r=K.dirname(i);if(r===i)break;e.push(K.basename(i)),i=r}let n=await li.realpath(i);return K.resolve(n,...e.reverse())}async function Id(t){try{return(await li.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Qr(t){let e=K.resolve(t);try{(await li.stat(e)).isDirectory()||(e=K.dirname(e))}catch(r){if(r.code!=="ENOENT")throw r}let i=e,n=K.resolve(PN.homedir());for(;;){if(!(e===n&&i!==n)){let o=K.join(e,...Xr.split("/")),s=e===i||await AN(o);if(await Ks(o)&&s)return e}if(await Ks(K.join(e,".git")))return e;let a=K.dirname(e);if(a===e)return i;e=a}}function Zr(t){return Ft(t)}async function xN(t,e){let i=Zr(e),n=K.resolve(t,...i.split("/")),r=await li.realpath(t),a=await cn(n);if(!sn(r,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Gs(t,e){let i=Zr(e),n=await xN(t,i),r=K.join(n,"comet");if(await Id(r))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([cn(n),cn(r)]);if(!sn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");return{projectRoot:K.resolve(t),configFile:K.join(t,...Xr.split("/")),artifactRoot:n,artifactRootRef:i,nativeRoot:r,specsDir:K.join(r,"specs"),changesDir:K.join(r,"changes"),archiveDir:K.join(r,"archive"),runtimeDir:K.join(r,"runtime"),locksDir:K.join(r,"runtime","locks"),transactionsDir:K.join(r,"runtime","transactions")}}function ae(t,e){return sn(K.resolve(t),K.resolve(e))}async function q(t,e){let i=K.resolve(t),n=K.resolve(e);if(!sn(i,n))throw new Error(`Path is outside the Native root: ${e}`);if(await Id(i))throw new Error(`Native root must not be a symbolic link: ${t}`);let[r,a]=await Promise.all([cn(i),cn(n)]);if(!sn(r,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}var Us=de;var ea=Wr;function IN(t="docs",e="en"){return qs(t,e)}async function qt(t){let e=(await Ws(t))?.config??null;return e?.native?e:null}async function ln(t){let e=await qt(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function _d(t){let e=await Qr(t.startPath),i=await qt(e);if(!i&&t.allowMissingConfig===!1)throw new Error(`${Xr} was not found`);if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let n=t.explicitArtifactRoot?Zr(t.explicitArtifactRoot):void 0;if(i&&n&&n!==i.native.artifact_root)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${n}`);let r=i??IN(n??"docs"),a=await Gs(e,r.native.artifact_root);return{config:r,paths:a,configured:i!==null}}import{promises as sb}from"fs";import cb from"path";import{AsyncLocalStorage as _N}from"async_hooks";import{randomUUID as $d}from"crypto";import{promises as ke}from"fs";import Hd from"os";import ce from"path";var Od=16*1024,Md=".coordinator",ON=5e3,jd=new _N,ta=new Map;function jN(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function $N(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let i=t;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: ${e}`);return i}function Ld(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function Ys(t,e){let i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return se(i,n)?F(i,n):F(i,n)&&t.size===e.size}function Xs(t,e){return Ys(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function et(t){let e,i;try{let n=await si(t,Od,{bigint:!0,label:"Native lock"});e=n.bytes,i=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof je?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Od} bytes: ${t}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:n}):new Error(`Native lock changed while reading: ${t}`,{cause:n}):n}return{file:t,owner:$N(JSON.parse(e.toString("utf8")),t),identity:Ld(i)}}async function HN(t){return(await et(t))?.owner??null}function Dd(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Hd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=qN(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function MN(t,e){try{await ke.lstat(e);return}catch(i){if(i.code!=="ENOENT")throw i}try{await ke.rename(t,e)}catch(i){if(i.code!=="ENOENT")throw i}}async function Qs(t,e){let i=await et(t.file);if(!i)return"missing";if(i.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Xs(i.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await ke.mkdir(e,{recursive:!0});let n=ce.join(e,`${ce.basename(t.file)}.${t.owner.id}.${$d()}.removed`);try{await ke.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let r=await et(n);if(!r||r.owner.id!==t.owner.id||!Ys(r.identity,t.identity))throw await MN(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await ke.rm(n,{force:!0}),"removed"}function Fd(t){return{id:$d(),pid:process.pid,hostname:Hd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Bd(t,e){let i;try{i=await ke.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let r=await HN(t);throw new Error(`Native lock is already held: ${t}${r?` by pid ${r.pid} for ${r.operation}`:""}`,{cause:n})}throw n}try{return await i.writeFile(JSON.stringify(e,null,2)+`
|
|
144
|
+
`,"utf8"),await i.sync(),Ld(await i.stat({bigint:!0}))}finally{await i.close()}}async function LN(t,e){let i=await q(t.nativeRoot,t.locksDir);await ke.mkdir(i,{recursive:!0});let n=await q(t.nativeRoot,ce.join(i,Md));await ke.mkdir(n,{recursive:!0});let r=Fd(e),a=ce.join(n,`.${r.id}.tmp`),o=ce.join(n,`${r.id}.claim`);try{let s=await Bd(a,r);await ke.rename(a,o);let c=await et(o);if(!c||!Ys(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.nativeRoot,locksDir:i,owner:r,identity:c.identity}}finally{await ke.rm(a,{force:!0})}}async function DN(t){let e=ce.dirname(t.file),i=!1,n=ce.basename(t.file);for(let r of await ke.readdir(e,{withFileTypes:!0})){if(!r.isFile()||r.isSymbolicLink()||!r.name.endsWith(".claim"))continue;let a=ce.join(e,r.name);if(ce.resolve(a)!==ce.resolve(t.file))try{let o=await et(a),s=Dd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Qs(o,e);continue}r.name<n&&(i=!0)}catch{r.name<n&&(i=!0)}}return i}async function qd(t){let e=await et(t.file);if(e){if(e.owner.id!==t.owner.id||!Xs(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Qs(e,ce.dirname(t.file))}}async function FN(t,e){let i=Date.now()+ON;for(;;){let n=await LN(t,e);if(!await DN(n))return n;if(await qd(n),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(r=>setTimeout(r,2+Math.floor(Math.random()*7)))}}async function BN(t){let e=ta.get(t)??Promise.resolve(),i,n=new Promise(a=>{i=a}),r=e.then(()=>n);return ta.set(t,r),await e,()=>{i(),ta.get(t)===r&&ta.delete(t)}}async function Vd(t,e,i){let n=ce.resolve(t.locksDir),r=jd.getStore();if(r?.has(n))return i();let a=await BN(n);try{let o=await FN(t,e),s=new Map(r??[]);return s.set(n,o),await jd.run(s,async()=>{try{return await i()}finally{await qd(o)}})}finally{a()}}async function un(t,e,i){return Vd(t,`acquire ${e}`,async()=>{let n=await q(t.nativeRoot,t.locksDir);await ke.mkdir(n,{recursive:!0});let r=await q(t.nativeRoot,ce.join(n,jN(e))),a=Fd(i),o=await Bd(r,a);return{file:r,nativeRoot:t.nativeRoot,locksDir:n,owner:a,identity:o}})}async function fn(t){await et(t.file)&&await Vd(t,`release ${ce.basename(t.file)}`,async()=>{let e=await et(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Xs(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let i=ce.join(t.locksDir,Md);await Qs(e,i)})}function qN(t){try{return process.kill(t,0),!0}catch(e){let i=e.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function zd(t){return Dd(await et(t))}import it from"path";import{TextDecoder as XN}from"util";import{createHash as VN}from"node:crypto";import{constants as ia,promises as $e}from"node:fs";import He from"node:path";import{TextDecoder as zN}from"node:util";function ra(t,e){let i=He.relative(t,e);return i===""||!He.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${He.sep}`)}function WN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function JN(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function KN(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function na(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Zs(t,e){let i=await $e.lstat(t);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await $e.realpath(t),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function GN(t,e,i){let n=He.resolve(t),r=He.resolve(e);if(!ra(n,r))throw new Error(`${i} is outside its managed root`);let a=[await Zs(n,i)],o=n;for(let s of He.relative(n,r).split(He.sep).filter(Boolean)){await Vt(a,i),o=He.join(o,s);let c=await Zs(o,i);if(!ra(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await Vt(a,i),a}async function Vt(t,e){for(let i of t){let n=await $e.lstat(i.path);if(!n.isDirectory()||n.isSymbolicLink()||!JN(i,n)||await $e.realpath(i.path)!==i.realPath)throw new Error(`${e} parent changed during I/O: ${i.path}`)}}async function UN(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function tt(t){let e=WN(t.maxBytes),i=He.resolve(t.file),n=await GN(t.root,He.dirname(i),t.label),r=await Promise.all((t.forbiddenRoots??[]).map(u=>Zs(He.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Vt(n,t.label);let a=await $e.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=KN(a),s=await $e.realpath(i);if(!ra(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(r.some(u=>ra(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?ia.O_RDONLY:ia.O_RDONLY|ia.O_NOFOLLOW|ia.O_NONBLOCK,l=await $e.open(i,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([$e.lstat(i),$e.realpath(i)]);if(await Vt(n,t.label),await Vt(r,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!na(o,u)||!na(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await UN(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),$e.lstat(i),$e.realpath(i)]);if(await Vt(n,t.label),await Vt(r,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!na(o,m)||!na(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:VN("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Wd(t){let e=await tt(t),i;try{i=new zN("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:i}}var QN=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),ZN=new Set(["id","type","source","target","staged","backup"]),eb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),tb=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Gd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var ib=256*1024,EA=1024*1024,RA=16*1024;var CA=64*1024*1024;var nb=new XN("utf-8",{fatal:!0});function oa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function sa(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function Ud(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function ec(t,e){if(typeof t!="string"||t.length===0||it.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function aa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Jd(t,e){if(ec(t,e),t.includes("\\")||t!==it.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function rb(t,e){let i=oa(t,`transaction operations[${e}]`);if(sa(i,ZN,`transaction operations[${e}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${e}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);ec(i.target,`transaction operation ${i.id} target`);for(let n of["source","staged","backup"])i[n]!==void 0&&ec(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 Yd(t){let e=oa(t,"Native Archive transaction journal");if(sa(e,eb,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!Gd.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Ud(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(aa(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=e.operations.map((s,c)=>{let l=oa(s,`Archive transaction operations[${c}]`);if(sa(l,tb,`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`);Jd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Jd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&aa(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(aa(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`);aa(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/${e.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:i}}function ab(t){let e=oa(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Yd(e);if(sa(e,QN,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!Gd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!it.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!it.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Ud(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let i=e.operations.map(rb),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:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:i}}function ob(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return it.join(t.transactionsDir,e)}function Xd(t,e){let i=ob(t,e);return{directory:i,journal:it.join(i,"transaction.json"),events:it.join(i,"events.jsonl"),staged:it.join(i,"staged"),backups:it.join(i,"backups")}}async function ic(t,e){let i=Xd(t,e);return await Promise.all(Object.values(i).map(n=>q(t.nativeRoot,n))),i}async function nc(t,e,i={}){let n=await ic(t,e),r=await tt({root:t.nativeRoot,file:n.journal,maxBytes:ib,label:`Native transaction journal ${e}`,hooks:i.hooks}),a=JSON.parse(nb.decode(r.bytes)),o=ab(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function lb(t,e){let i;try{i=await sb.readdir(t.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 nc(t,n.name);if(r.id!==e&&r.status!=="committed"&&r.status!=="rolled-back")return!0}catch{return!0}return!1}async function ub(t,e){let i=Date.now()+5e3,n=cb.join(t.locksDir,"root-move.lock");for(;;)try{return await un(t,"root-move",e)}catch(r){if(r.cause?.code!=="EEXIST")throw r;let o=await zd(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 kt(t,e,i,n){let r=await ub(t,e);try{if(await ln(t.projectRoot),await lb(t,n?.allowedTransactionId))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fn(r)}}function Qd(t){return Number.isSafeInteger(t)&&t>=1}async function Zd(t){if(!Qd(t.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(t.next.revision!==t.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let e=await t.read();if(!Qd(e.revision))throw new Error("Native current revision must be a positive integer");let i=t.equals??((n,r)=>JSON.stringify(n)===JSON.stringify(r));if(e.revision===t.next.revision&&i(e,t.next))return e;if(e.revision!==t.expectedRevision)throw t.conflict(e.revision);return await t.write(t.next),t.next}import{createHash as fa}from"crypto";import{spawn as uh}from"node:child_process";import{promises as U}from"fs";import V from"path";import{createHash as fb}from"crypto";function G(t){return fb("sha256").update(t).digest("hex")}var ca={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},fh=1e3,db=8*1024*1024,hb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pb=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),mb=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),vb=new Set(["schema","include","exclude","hash"]),gb=new Set(["provider","gitSelection","physicalSelection","projection"]),wb=new Set(["provider","selection"]),yb=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Nb=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),bb=new Set(["schema","status","before","after"]),Sb=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),kb=new Set(["path","hash","size","type","gitObjectId"]),Eb=new Set(["path","size","type","reason"]),Rb=new Set(["ref","hash","count"]),Cb=new Set(["change-created","legacy-migration","explicit"]),Pb=new Set(["file","directory","other"]),Ab=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"]),da=/^[a-f0-9]{64}$/u,dh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,xb=new Set(["EACCES","EPERM"]),di=64*1024,lc=64*1024,Tb=6e4,Ib=1e3,_b=2,hh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Ob={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function jb(t){let e=t.deadlineMs??Tb;if(!Number.isSafeInteger(e)||e<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+e,gitProcess:t.gitProcess??{command:"git"}}}function Me(t){return Math.max(0,t.deadlineAt-Date.now())}function _(t){return Me(t)>=1}function rc(t){let e=t===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:t});return Object.assign(e,{code:"GIT_SNAPSHOT_TIMEOUT"})}function dn(t){return t.code==="GIT_SNAPSHOT_TIMEOUT"}function $b(t){let e={...Ob,...t};if(!Number.isSafeInteger(e.maxNodes)||e.maxNodes<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxPathBytes)||e.maxPathBytes<1||e.maxPathBytes>e.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return e}async function Hb(t,e){if(e.terminateTree){await e.terminateTree(t);return}let i=t.pid;if(i===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&V.win32.isAbsolute(n)?V.win32.resolve(n):"C:\\Windows",a=V.win32.join(r,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.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,f=(d,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(d))};try{l=uh(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>f(!1)),l.once("close",d=>f(d===0)),u=setTimeout(()=>f(!1,!0),Ib),u.unref()}catch{f(!1)}});for(let s=0;s<_b;s+=1)if(await o()){t.kill("SIGKILL");return}throw t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.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}t.kill("SIGKILL")}function fc(t,e,i,n){let r=Me(t);if(r<1)throw rc();let a=t.gitProcess,o=uh(a.command,[...a.argsPrefix??[],"-C",e,...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)}),f=setTimeout(()=>{c=!0,l=Hb(o,a).then(()=>({error:null}),p=>({error:p}))},r);f.unref();let d=u.then(async p=>{if(clearTimeout(f),c){let m=await l;throw m?.error?rc(m.error):rc()}return{code:p,spawnError:s}});return{child:o,completion:d}}function Mb(t){let e={...hh,...t};if(!Number.isSafeInteger(e.maxRecords)||e.maxRecords<1||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<1||!Number.isSafeInteger(e.maxRecordBytes)||e.maxRecordBytes<1||e.maxRecordBytes>e.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return e}async function la(t,e,i,n=lc){let{child:r,completion:a}=fc(t,e,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>=di)return;let m=di-c,h=Buffer.from(p).subarray(0,m);s.push(h),c+=h.byteLength});let{code:f,spawnError:d}=await a;if(f===0&&d===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${d?`: ${d.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function ac(t){return{hash:t.digest,recordCount:t.recordCount,storedRecordCount:t.records.length,stdoutBytes:t.stdoutBytes,overflow:t.overflow}}function oc(t,e,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}=fc(t,e,i,n.stdin!==void 0),c=[],l=fa("sha256"),u=[],f=0,d=0,p=0,m=0,h=Buffer.alloc(0),v=!1,w=!1,E=!1,k=N=>{let S=0;for(;S<N.byteLength;){let g=N.indexOf(0,S),b=g<0?N.byteLength:g,y=N.subarray(S,b);if(!v&&y.byteLength>0&&(h.byteLength+y.byteLength>n.maxRecordBytes?(h=Buffer.alloc(0),v=!0,w=!0):h=Buffer.concat([h,y])),g<0)break;m+=1,h.byteLength===0&&!v&&(E=!0);let R=h.byteLength+1;!v&&m<=n.maxRecords&&p+R<=n.maxBytes?(c.push(h),p+=R):w=!0,h=Buffer.alloc(0),v=!1,S=g+1}};o.stdout.on("data",N=>{l.update(N),d+=N.byteLength,d>n.maxBytes&&(w=!0);let S=n.outputChunkBytes;if(S===void 0){k(N);return}for(let g=0;g<N.byteLength;g+=S)k(N.subarray(g,Math.min(N.byteLength,g+S)))}),o.stderr.on("data",N=>{if(f>=di)return;let S=di-f,g=Buffer.from(N).subarray(0,S);u.push(g),f+=g.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:S})=>{let g=n.acceptedExitCodes??[0];if(N!==null&&g.includes(N)&&S===null&&!E&&h.byteLength===0&&!v){r({records:c,digest:l.digest("hex"),overflow:w,recordCount:m,stdoutBytes:d});return}a(new Error(`git ${i.join(" ")} failed${S?`: ${S.message}`:E||h.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),n.stdin&&o.stdin?.end(n.stdin)})}function eh(t){let e=t.toString("utf8");if(!Buffer.from(e,"utf8").equals(t))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return e}async function Lb(t,e,i){let{child:n,completion:r}=fc(t,e,i,!1),a=[],o=0,s=!1;n.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),n.stderr.on("data",u=>{if(o>=di)return;let f=di-o,d=Buffer.from(u).subarray(0,f);a.push(d),o+=d.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 ua(t){let e=t.endsWith("/")?t.slice(0,-1):t;return e.length===0||e.includes("\\")||V.posix.isAbsolute(e)||/^[A-Za-z]:/u.test(e)||V.posix.normalize(e)!==e||e===".."||e.startsWith("../")||e.includes("\0")?null:e}function Db(t,e){return t.map(i=>{let n=ua(i);if(n===null)throw new Error(`Native Git snapshot provider returned an unsafe ${e} path`);return n})}async function Fb(t){let e=V.resolve(t);for(;;){try{return await U.lstat(V.join(e,".git")),!0}catch(n){if(n.code!=="ENOENT")throw n}let i=V.dirname(e);if(i===e)return!1;e=i}}async function ph(t,e,i,n={}){let r={...i,...n.outputChunkBytes===void 0?{}:{outputChunkBytes:n.outputChunkBytes}},a=await oc(t,e,["ls-files","--stage","-z"],r);await n.afterStageBefore?.();let o=await oc(t,e,["ls-files","--cached","--others","--exclude-standard","-z"],r);await n.afterCombined?.();let s=await oc(t,e,["ls-files","--stage","-z"],r);return{stagedBefore:a,combined:o,stagedAfter:s}}function mh(t){return{stageBefore:ac(t.stagedBefore),combined:ac(t.combined),stageAfter:ac(t.stagedAfter)}}async function Bb(t,e,i=hh,n={}){if(!await Fb(e))return null;let r;try{r=await la(t,e,["rev-parse","--is-inside-work-tree"])}catch(w){throw dn(w)?w:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:w})}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 ph(t,e,i,n)}catch(w){throw dn(w)?w:new Error("Native Git snapshot provider failed after repository detection",{cause:w})}let{stagedBefore:o,combined:s,stagedAfter:c}=a,l=new Set,u=new Map,f=new Set,d=w=>{for(let E of w){let k=eh(E),N=k.indexOf(" ");if(N<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(k.slice(0,N))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let g=ua(k.slice(N+1));if(g===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");l.add(g),S.stage==="0"&&u.set(g,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(g)}};d(o.records),d(c.records);let p=s.records.map(eh),m=Db(p,"combined"),h=new Set(m.filter(w=>!l.has(w))),v=new Set(m.filter((w,E)=>!l.has(w)&&p[E].endsWith("/")));for(let w of f)v.delete(w);return{tracked:l,trackedObjectIds:u,untracked:h,gitlinks:f,nestedRepositories:v,omissions:[],overflow:null,evidence:null,initialFence:mh(a)}}function Rt(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function th(t){return t.stageBefore.overflow||t.combined.overflow||t.stageAfter.overflow}function qb(t,e){return!Rt(t.stageBefore,t.stageAfter)||!Rt(t.stageAfter,e.stageBefore)||!Rt(t.combined,e.combined)||!Rt(e.stageBefore,e.stageAfter)}async function Vb(t,e,i,n,r){let a;try{a=await ph(t,e,i,{...r===void 0?{}:{outputChunkBytes:r}})}catch(u){throw dn(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=n.initialFence,s=mh(a),c=th(o)||th(s),l=qb(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:G(`comet.native.git-selection-overflow.v2
|
|
145
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var zb=(1n<<256n)-1n;function Wb(t){return t.isFile()?"file":t.isDirectory()?"directory":t.isSymbolicLink()?"symlink":"other"}async function ih(t){let e=V.resolve(t.paths.projectRoot),i=V.resolve(t.paths.nativeRoot),n=V.resolve(t.paths.configFile),r=V.join(e,".comet","current-change.json"),a=[],o=[],s=Buffer.alloc(32),c=0n,l=0,u=0,f=0,d=!1,p=!1,m=!1,h=()=>Me(t.execution)>=1?!0:(d=!0,m=!0,!1),v=k=>{let N=Buffer.from(`${k.type}\0${k.path}`,"utf8"),S=fa("sha256").update("comet.native.physical-selection-record.v1\0").update(N).digest();for(let g=0;g<s.length;g+=1)s[g]^=S[g];if(c=c+BigInt(`0x${S.toString("hex")}`)&zb,u+=1,f+=N.byteLength,Buffer.byteLength(k.path,"utf8")>t.limits.maxPathBytes||f>t.limits.maxBytes){d=!0,m=!0;return}a.push(k)},w=async k=>{if(m||!h())return;let N;try{N=await U.opendir(k)}catch(R){if(!h())return;if(!ee(R)&&!Z(R)||k===e&&ee(R))throw R;p||=Z(R),d||=ee(R),m=!0;return}if(!h()){try{await N.close()}catch(R){if(R.code!=="ERR_DIR_CLOSED")throw R}return}let S=!1,g;try{for(;!m&&h();){let R;try{R=await N.read()}catch(J){if(!h())break;if(!ee(J)&&!Z(J)||k===e&&ee(J))throw J;p||=Z(J),d||=ee(J),m=!0;break}if(!h()||R===null)break;if(l+=1,l>t.limits.maxNodes){d=!0,m=!0;break}let O=V.join(k,R.name),B=Ub(e,O);if(O===n||O===r||Ct(i,O)||t.denylist.some(J=>Ct(J,O))||We(B)!==null)continue;if(!h())break;let H;try{H=await U.lstat(O)}catch(J){if(!h())break;if(!ee(J)&&!Z(J))throw J;if(p=!0,v({path:B,type:"other"}),o.push({path:B,size:null,type:"file",reason:ee(J)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(B),m||!h())break;continue}if(!h())break;let D=Wb(H);if(D==="directory"){if(Zb(t.policy,B))continue;if(!h())break;let J;try{J=await U.realpath(O)}catch(Be){if(!h())break;if(!ee(Be)&&!Z(Be))throw Be;if(p=!0,v({path:B,type:D}),o.push({path:B,size:null,type:"directory",reason:ee(Be)?"unreadable":"changed-during-read"}),await t.hooks?.afterNode?.(B),m||!h())break;continue}if(!h())break;if(!ae(t.physicalProjectRoot,J)||Ct(t.physicalNativeRoot,J))continue;if(v({path:B,type:D}),await t.hooks?.afterNode?.(B),!h()||(await w(O),m))break;continue}if(v({path:B,type:D}),await t.hooks?.afterNode?.(B),!h()||m)break}}catch(R){S=!0,g=R}let b;try{await N.close()}catch(R){b=R}let y=h();if(S)throw g;if(y&&b!==void 0&&b.code!=="ERR_DIR_CLOSED")throw b};await w(e),h(),d?(a.length=0,u=0,f=0):(a.sort((k,N)=>k.path.localeCompare(N.path,"en")),o.sort((k,N)=>k.path.localeCompare(N.path,"en")));let E=d?G(`comet.native.physical-selection-incomplete.v1
|
|
146
146
|
${JSON.stringify({maxNodes:t.limits.maxNodes,maxBytes:t.limits.maxBytes,maxPathBytes:t.limits.maxPathBytes})}`):G(`comet.native.physical-selection.v1
|
|
147
|
-
${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:f,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:E,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:f,overflow:d,unstable:p}}}function vh(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function
|
|
148
|
-
`)}function
|
|
149
|
-
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function sc(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function
|
|
147
|
+
${JSON.stringify({visitedNodeCount:l,recordCount:u,encodedBytes:f,xor:s.toString("hex"),sum:c.toString(16).padStart(64,"0")})}`);return{records:a,omissions:o,evidence:{hash:E,visitedNodeCount:l,recordCount:u,storedRecordCount:a.length,encodedBytes:f,overflow:d,unstable:p}}}function vh(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function Jb(t,e){let i=t.overflow||e.overflow,n=t.unstable||e.unstable||!vh(t,e),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:t,after:e}:null}}function Kb(t){return[...new Set([...t.tracked,...t.untracked])].sort((e,i)=>e.localeCompare(i,"en"))}async function nh(t,e){let n=(await la(t,e,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!dh.test(n))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return G(`gitlink:${n}`)}async function rh(t,e){let i=await nh(t,e),n=await Lb(t,e,["status","--porcelain=v1","-z","--untracked-files=normal"]),r=await nh(t,e);if(r!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:r,dirty:n}}function Gb(t,e){if(We(e)!==null)return!1;let i=V.resolve(t.projectRoot,...e.split("/"));return!Ct(V.resolve(t.nativeRoot),i)}function Ub(t,e){return V.relative(t,e).split(V.sep).join("/")}function Yb(t,e){return e.map(i=>V.resolve(t,...i.split(/[\\/]/u)))}function Ct(t,e){let i=V.resolve(t),n=V.resolve(e);return n===i||ae(i,n)}function ee(t){return xb.has(t.code??"")}function Z(t){return t.code==="ENOENT"}function gh(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
148
|
+
`)}function Xb(t,e){return G(`comet.native.snapshot-policy.v1
|
|
149
|
+
${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function sc(t,e,i){let n=new Set(e),r=[...e];for(;r.length>0;){if(i&&!i())return null;let a=r.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),r.push(a+1))}return n}function Qb(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function ah(t){let e=ea(t,"Native snapshot pattern"),i=[];for(let n=0;n<e.length;n+=1){let r=e[n];r==="*"&&e[n+1]==="*"?(n+=1,e[n+1]==="/"?(n+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):r==="*"?i.push({kind:"star"}):r==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:r})}return(n,r)=>{let a=r?Qb(r):void 0;if(a&&!a())return!1;let o=sc(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=sc(i,c,a),o===null||o.size===0)return!1}return sc(i,o,a)?.has(i.length)??!1}}function wh(t){if(t===void 0)return;let e=[...new Set(t.include.map(r=>ea(r,"include")))].sort((r,a)=>r.localeCompare(a,"en")),i=[...new Set(t.exclude.map(r=>ea(r,"exclude")))].sort((r,a)=>r.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=Xb(e,i);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:i,hash:n},includeMatchers:e.map(ah),excludeMatchers:i.map(ah),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 Zb(t,e){return t?.excludedDirectoryPrefixes.includes(e)??!1}function oh(t,e,i){if(!t)return!0;let n=()=>_(i),r=!1;for(let a of t.includeMatchers){if(!n())return!1;if(a(e,n)){r=!0;break}}if(!r)return!1;for(let a of t.excludeMatchers)if(!n()||a(e,n))return!1;return!0}function cc(t,e,i){let n=JSON.stringify(i);return G(`${t}
|
|
150
150
|
${Buffer.byteLength(e)}:${e}
|
|
151
|
-
${Buffer.byteLength(n)}:${n}`)}function uc(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function sh(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!uc(i))return t.splice(e,1),i}return null}function Et(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Zb(t,e,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await U.open(t,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=fa("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,e+1)),s=0;try{if(!_(n))return{status:"budget-exhausted"};let c=await r.stat();if(!_(n))return{status:"budget-exhausted"};if(!c.isFile()||!Et(i,c))return{status:"changed"};for(;;){if(!_(n))return{status:"budget-exhausted"};let l=e+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 f=await r.stat();return _(n)?!f.isFile()||!Et(c,f)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:f}:{status:"budget-exhausted"}}if(s+u.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Ee(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Re(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function fi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Je(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function yh(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=V.posix.normalize(t);if(i!==t||V.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function eS(t,e){let i=Ee(t,`Native snapshot entry ${e}`);Re(i,Sb,`Native snapshot entry ${e}`);let n=yh(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!da.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:Je(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!dh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function tS(t,e){let i=Ee(t,`Native snapshot omission ${e}`);if(Re(i,kb,`Native snapshot omission ${e}`),!Cb.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Pb.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:yh(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:Je(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function iS(t){let e=Ee(t,"Native snapshot omission overflow");if(Re(e,Eb,"Native snapshot omission overflow"),typeof e.hash!="string"||!da.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:fi(e.count,"Native snapshot omission overflow count")}}function ui(t,e){let i=Ee(t,e);if(Re(i,yb,e),typeof i.hash!="string"||!da.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Je(i.recordCount,`${e} recordCount`),r=Je(i.storedRecordCount,`${e} storedRecordCount`),a=Je(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function ch(t){let e=Ee(t,"Native Git selection evidence");if(Re(e,wb,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ui(e.stageBefore,"Native Git selection stageBefore"),n=ui(e.combined,"Native Git selection combined"),r=ui(e.stageAfter,"Native Git selection stageAfter"),a=ui(e.finalStageBefore,"Native Git selection finalStageBefore"),o=ui(e.finalCombined,"Native Git selection finalCombined"),s=ui(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(f=>f.overflow),l=!Rt(i,r)||!Rt(r,a)||!Rt(n,o)||!Rt(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(e.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 lh(t,e){let i=Ee(t,e);if(Re(i,bb,e),typeof i.hash!="string"||!da.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=Je(i.visitedNodeCount,`${e} visitedNodeCount`),r=Je(i.recordCount,`${e} recordCount`),a=Je(i.storedRecordCount,`${e} storedRecordCount`),o=Je(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function nS(t){let e=Ee(t,"Native physical selection evidence");if(Re(e,Nb,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=lh(e.before,"Native physical selection before"),n=lh(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!vh(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function hn(t){let e=Ee(t,"Native content snapshot manifest");if(Re(e,hb,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Rb.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Ee(e.capture,"Native content snapshot capture");if(Re(g,vb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let b=g.gitSelection===void 0?void 0:ch(g.gitSelection),y=g.physicalSelection===void 0?void 0:nS(g.physicalSelection),R=null;if(g.projection!==void 0){let O=Ee(g.projection,"Native content snapshot projection");if(Re(O,gb,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");R={provider:"git",...O.selection===void 0?{}:{selection:ch(O.selection)}}}if(g.provider==="git"){if(y||R)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...b?{gitSelection:b}:{}}}else{if(b)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(y&&R)throw new Error("Native physical-tree capture cannot combine selection and projection");i=R?{provider:"physical-tree",projection:R}:{provider:"physical-tree",...y?{physicalSelection:y}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Ee(e.limits,"Native content snapshot limits");Re(n,pb,"Native content snapshot limits");let r={maxFiles:fi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:fi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Ee(e.policy,"Native snapshot policy");if(Re(g,mb,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=wh({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(eS),s=e.omitted.map(tS),c=Je(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:iS(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>r.maxFileBytes)||o.reduce((g,b)=>g+b.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>fh||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(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.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!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let E=i?.physicalSelection,k=E?.status==="overflow"||E?.status==="overflow-and-changed",N=E?.status==="changed"||E?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let S={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(gh(S)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return S}function rS(t,e){if(!db.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=V.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return V.join(i,"runtime","baseline-manifest.json")}async function Nh(t,e={}){let i={maxFiles:e.limits?.maxFiles??ca.maxFiles,maxFileBytes:e.limits?.maxFileBytes??ca.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??ca.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??ca.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},n=wh(e.policy),r=Ob({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=Hb(e.gitSelectionLimits),o=jb(e.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=V.resolve(t.projectRoot),c=await U.realpath(s),l=V.resolve(t.nativeRoot),u=await U.realpath(l),f=V.resolve(t.configFile),d=V.join(s,".comet","current-change.json"),p=Ub(s,e.denylist??[]),m=[],h=[],v=new Map,w=new Map,E=0,k=0,N=G("comet.native.snapshot-omission-overflow.v1"),S=0,g=!1,b=null,y=P=>{k+=1,N=cc(N,"omission",P)},R=P=>{if(E+=1,h.length<fh){h.push(P);return}if(uc(P)){let A=sh(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),h.push(P);return}y(P)},O=P=>{E+=P.count,k+=P.count,N=cc(N,"git-selection",{source:"git-selection",...P})},B=P=>{k+=1,N=cc(N,"manifest-entry",{reason:"manifest-size",entry:P})},H=async(P,A)=>{m.push(P),S+=P.size,v.set(P.path,A),g||(g=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(P.path))},D=(P,A)=>{let T=m.findIndex(X=>X.path===P);if(T<0)return;let[$]=m.splice(T,1);S-=$.size,v.delete(P),R(A)},J=async(P,A,T,$)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let X;try{X=await U.realpath(P)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:T.size,type:"file",reason:Z(I)?"changed-during-read":"unreadable"});return}if(!_(r)||!ae(c,X)||Ct(u,X))return;if(m.length>=i.maxFiles){R({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){R({path:A,size:T.size,type:"file",reason:"file-size"});return}if(S+T.size>i.maxTotalBytes){R({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,j,x;try{if(L=await Zb(X,T.size,T,r),L.status==="budget-exhausted"||!_(r))return;if(L.status==="changed"){R({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(x=await U.realpath(P),!_(r)))return;j=await U.lstat(P)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:T.size,type:"file",reason:Z(I)?"changed-during-read":"unreadable"});return}if(_(r)){if(L.bytes!==T.size||x!==X||!Et(T,L.finalStat)||!Et(L.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){R({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await H({path:A,hash:L.hash,size:j.size,type:"file",...$===void 0?{}:{gitObjectId:$}},{kind:"file",target:P,realTarget:X,stat:j})}},Be=async(P,A,T)=>{if(!_(r))return;let $,X,L;try{if($=await U.readlink(P,{encoding:"buffer"}),!_(r)||(L=await U.lstat(P),!_(r)))return;X=await U.readlink(P,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:null,type:"other",reason:Z(I)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!L.isSymbolicLink()||!Et(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!$.equals(X)){R({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=$.byteLength;if(m.length>=i.maxFiles){R({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){R({path:A,size:j,type:"other",reason:"file-size"});return}if(S+j>i.maxTotalBytes){R({path:A,size:j,type:"other",reason:"total-size"});return}let x=fa("sha256").update("symlink\0").update($).digest("hex");_(r)&&await H({path:A,hash:x,size:j,type:"file"},{kind:"symlink",target:P,rawTarget:$,stat:L})},qe=async()=>{for(let[P,A]of[...v]){if(!_(r))return;if(A.kind==="file"){let j,x;try{if(j=await U.realpath(A.target),!_(r))return;x=await U.lstat(A.target)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;D(P,{path:P,size:null,type:"file",reason:ee(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(j!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!Et(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&D(P,{path:P,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,x;try{if(j=await U.lstat(A.target),!_(r))return;x=await U.readlink(A.target,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;D(P,{path:P,size:null,type:"other",reason:ee(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!Et(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&D(P,{path:P,size:null,type:"other",reason:"changed-during-read"});continue}let T,$;try{if(T=await U.realpath(A.target),!_(r))return;$=await U.lstat(A.target)}catch{if(!_(r))return;D(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&$.isDirectory()&&!$.isSymbolicLink()&&Et(A.stat,$)&&ae(c,T)&&!Ct(u,T))){D(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!_(r))return;L=await rh(r,T)}catch(j){if(dn(j))throw j;D(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;L.dirty?D(P,{path:P,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&D(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"})}for(let[P,A]of w){if(!_(r))return;try{let T=await U.lstat(A);if(!_(r))return;R({path:P,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!_(r))return;if(Z(T))continue;if(!ee(T))throw T;R({path:P,size:null,type:"file",reason:"unreadable"})}}},me=await Fb(r,s,a,e.gitSelectionHooks);if(me===null){let P=await ih({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:e.physicalSelectionHooks});await e.physicalSelectionHooks?.afterInitialSelection?.();for(let $ of P.records){if($.type!=="file"&&$.type!=="symlink"||v.has($.path))continue;if(Me(r)<1)break;if(!oh(n,$.path,r))continue;if(Me(r)<1)break;let X=V.resolve(s,...$.path.split("/")),L;try{L=await U.lstat(X)}catch(j){if(!_(r))break;if(!ee(j)&&!Z(j))throw j;R({path:$.path,size:null,type:"file",reason:Z(j)?"changed-during-read":"unreadable"});continue}if(Me(r)<1)break;if($.type==="symlink"&&L.isSymbolicLink()){if(await Be(X,$.path,L),Me(r)<1)break;continue}if($.type!=="file"||!L.isFile()||L.isSymbolicLink()){R({path:$.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(X,$.path,L),Me(r)<1)break}Me(r)>=1&&await qe();let A=await ih({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=Wb(P.evidence,A.evidence);b=T.evidence;for(let $ of[...P.omissions,...A.omissions,...T.omissions])h.some(X=>X.path===$.path&&X.reason===$.reason)||R($)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let P=e.incrementalBaseline,A=new Map,T=!1;if(P){let x=hn(P);for(let I of x.entries)I.gitObjectId!==void 0&&A.set(I.path,I);T=A.size>0}let $=new Set,X=!0;try{let x=await la(r,s,["ls-files","--modified","-z"],lc);for(let I of x.toString("utf8").split("\0")){let ie=ua(I);ie!==null&&$.add(ie)}}catch{T=!1,X=!1,A.clear()}let L=new Set,j=new Set;for(let x of Jb(me)){if(v.has(x)||!Kb(t,x))continue;if(Me(r)<1)break;if(!oh(n,x,r))continue;if(Me(r)<1)break;let I=V.resolve(s,...x.split("/"));if(I===f||I===d||p.some(ge=>Ct(ge,I)))continue;if(me.gitlinks.has(x)){if(m.length>=i.maxFiles){R({path:x,size:0,type:"file",reason:"file-count"});continue}let ge,Dn;try{[ge,Dn]=await Promise.all([U.realpath(I),U.lstat(I)])}catch{R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Dn.isSymbolicLink()||!Dn.isDirectory()||!ae(c,ge)||Ct(u,ge)){R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ut=await rh(r,ge);if(Ut.dirty){R({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await H({path:x,hash:Ut.hash,size:0,type:"file"},{kind:"gitlink",target:I,realTarget:ge,stat:Dn,hash:Ut.hash})}catch(Ut){if(dn(Ut))throw Ut;R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ie;try{ie=await U.lstat(I)}catch(ge){if(Z(ge)&&me.tracked.has(x)){w.set(x,I);continue}if(!ee(ge)&&!Z(ge))throw ge;R({path:x,size:null,type:"file",reason:Z(ge)?"changed-during-read":"unreadable"});continue}if(ie.isSymbolicLink()){await Be(I,x,ie);continue}if(!ie.isFile()){me.nestedRepositories.has(x)||R({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Pe=me.trackedObjectIds.get(x),ve=Pe?A.get(x):void 0;if(T&&ve?.gitObjectId!==void 0&&ve.gitObjectId===Pe&&!$.has(x)){if(m.length>=i.maxFiles){R({path:x,size:ve.size,type:"file",reason:"file-count"});continue}if(ve.size>i.maxFileBytes){R({path:x,size:ve.size,type:"file",reason:"file-size"});continue}if(S+ve.size>i.maxTotalBytes){R({path:x,size:ve.size,type:"file",reason:"total-size"});continue}m.push({...ve}),S+=ve.size,L.add(x);continue}let Rl=X&&!$.has(x)?Pe:void 0;await J(I,x,ie,Rl),Rl!==void 0&&j.add(x)}if(await qe(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await qb(r,s,a,me,e.gitSelectionHooks?.outputChunkBytes),L.size>0||T&&j.size>0){let x=await la(r,s,["ls-files","--modified","-z"],lc),I=new Set;for(let ie of x.toString("utf8").split("\0")){let Pe=ua(ie);Pe!==null&&I.add(Pe)}for(let ie of L){if(!I.has(ie))continue;let Pe=m.find(ve=>ve.path===ie);D(ie,{path:ie,size:Pe?.size??null,type:"file",reason:"changed-during-read"})}for(let ie of j){if(!I.has(ie))continue;let Pe=m.find(ve=>ve.path===ie);Pe&&delete Pe.gitObjectId}}for(let x of me.omissions)R(x);me.overflow&&O(me.overflow)}m.sort((P,A)=>P.path.localeCompare(A.path,"en")),h.sort((P,A)=>P.path.localeCompare(A.path,"en"));let hm=me===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...me.evidence?{gitSelection:me.evidence}:{}},El=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:hm,createdAt:(e.now??new Date).toISOString(),complete:E===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:E,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}}),Ya=El();for(;gh(Ya)>i.maxManifestBytes;){if(h.filter(A=>!uc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let $=sh(h);if($===null)break;y($)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))E+=1,B(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ya=El()}return Ya}async function dc(t,e,i={}){let r=(await qt(t.projectRoot))?.native.snapshot??Us;return Nh(t,{...i,policy:e.policy,incrementalBaseline:e,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 bh(t,e){let i=rS(t,e);await q(t.nativeRoot,i);try{let n=await Wd({root:t.nativeRoot,file:i,maxBytes:fb,label:"Native baseline snapshot manifest"});return hn(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as bS}from"crypto";import wc from"path";var Ke=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{constants as pa,promises as le}from"node:fs";import ye from"node:path";import{TextDecoder as mS}from"node:util";import fS from"path";var Sh=(t,e)=>{let i=t[e];return i==null?null:String(i)};function mn(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function pn(t,e){let i=mn(t,e);if(fS.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function dS(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}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 kh(t){if(!t.run_id)return null;let e=mn(t,"run_id"),i=mn(t,"skill"),n=mn(t,"skill_version"),r=mn(t,"skill_hash"),a=pn(t,"pending_ref"),o=pn(t,"trajectory_ref"),s=pn(t,"context_ref"),c=pn(t,"artifacts_ref"),l=pn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:n,skillHash:r,orchestration:t.orchestration,currentStep:Sh(t,"current_step"),iteration:u,pending:Sh(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:dS(t)}}var Dx=256*1024;var hS=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function pS(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)},i=kh(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Run state: stored value must be an object");let e=t,i=Object.keys(e).find(n=>!hS.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(e.currentStep!==null&&(typeof e.currentStep!="string"||e.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(e.pending!==null&&(typeof e.pending!="string"||e.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!e.retries||typeof e.retries!="object"||Array.isArray(e.retries))throw new Error("Invalid Run state: retries must be an object");return pS(e)}var we={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 gn(t,e){let i=ye.relative(t,e);return i===""||!ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ye.sep}`)}function Rh(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function vn(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}function vS(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function hi(t,e,i){let n=Ke[e];if(i!==void 0&&i!==n)throw new Error(`Native Run ${e} ref must be ${n}`);let r=ye.resolve(t),a=ye.resolve(r,...n.split("/"));if(!gn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Eh(t){let e=await le.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function hc(t,e){let i=ye.resolve(t),n=ye.resolve(e);if(!gn(i,n))throw new Error("Native Run path is outside its change");let r=[await Eh(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 Eh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!gn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ma(t){for(let e of t){let i=await le.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!vS(e,i)||await le.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function gS(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function wn(t,e,i,n,r){let a=await hc(t,ye.dirname(e));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await le.lstat(e)}catch(f){if(f.code==="ENOENT")return null;throw f}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=Rh(o),c=await le.realpath(e);if(!gn(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?pa.O_RDONLY:pa.O_RDONLY|pa.O_NOFOLLOW|pa.O_NONBLOCK,u;try{u=await le.open(e,l)}catch(f){throw new Error(`${n} changed while opening`,{cause:f})}try{let[f,d,p]=await Promise.all([u.stat(),le.lstat(e),le.realpath(e)]);if(await ma(a),!f.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!vn(s,f)||!vn(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await gS(u,i,n);await r?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([u.stat(),le.lstat(e),le.realpath(e)]);if(await ma(a),!v.isFile()||v.isSymbolicLink()||w!==c||!vn(s,h)||!vn(s,v))throw new Error(`${n} changed while reading`);let E;try{E=new mS("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${n} is not valid UTF-8`,{cause:k})}return{text:E,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function wS(t,e,i){let n=await hc(t,ye.dirname(e));if(!n)return{exists:!1};let r;try{r=await le.lstat(e)}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 le.realpath(e);if(!gn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ma(n),{exists:!0,identity:Rh(r),realPath:a}}async function yS(t,e,i,n){let r=await hc(t,ye.dirname(e));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await le.lstat(e)}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()||!vn(i.identity,a)||await le.realpath(e)!==i.realPath)throw new Error(`${n} changed before commit`);await ma(r)}async function pc(t){if(Buffer.byteLength(t.content,"utf8")>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);let i=t.expected??await wS(t.changeDir,t.file,t.label);if(i.exists&&i.identity.size>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);await Ze(t.file,t.content,{containedRoot:t.changeDir,beforeCommit:async()=>{await t.hooks?.beforeCommit?.(),await yS(t.changeDir,t.file,i,t.label)}});let n=await wn(t.changeDir,t.file,t.maxBytes,t.label);if(!n||n.text!==t.content)throw new Error(`${t.label} commit could not be verified`)}function NS(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function Ch(t){return`${JSON.stringify(t,null,2)}
|
|
152
|
-
`}function mc(t){return ha(t)}async function yn(t,e){let i=hi(t,"stateRef"),n=await wn(t,i,we.runStateBytes,"Native Run state",e);return n?ha(
|
|
153
|
-
`;if(Buffer.byteLength(a,"utf8")>we.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${we.trajectoryEventBytes} bytes`);let o=await wn(t,r,we.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=we.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${we.trajectoryEvents} events`);await pc({changeDir:t,file:r,content:`${o?.text??""}${a}`,maxBytes:we.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function xh(t,e,i,n){await pc({changeDir:t,file:hi(t,"checkpointRef",e),content:Ch(i),maxBytes:we.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var
|
|
154
|
-
`)])}catch(f){if(!
|
|
155
|
-
`);function En(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jh(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function kc(t){if(!Oh.test(t))throw new Error(`Invalid Native change name: ${t}`)}function HS(t){if(!Oh.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function $h(t,e){if(t.length===0||nt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function MS(t,e){let i=En(t,`spec_changes[${e}]`);if(jh(i,IS,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(HS(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"&&$h(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"||!Sc.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"||!Sc.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 LS(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Ec(t,e){if(jh(t,e,At),typeof t.name!="string")throw new Error("Native change name is required");if(kc(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!_S.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!OS.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(MS),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!jS.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&$h(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!LS(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Rn(t){let e=En(t,At);if(e.schema!==Wt)throw new Error(`Expected ${Wt}`);return{schema:Wt,...Ec(e,xS)}}function kn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Nc(t,e,i){if(t===null)return null;let n=typeof t=="string"?$S.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function DS(t){if(t==null)return null;if(typeof t!="string"||!Sc.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function FS(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Cn(t){let e=En(t,At);if(e.schema!==zt)throw new Error(`Expected ${zt}`);if(kn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${zt} minimum_runtime_version must be 2`);return{schema:zt,minimum_runtime_version:2,revision:kn(e.revision,"Native v2 revision"),...Ec(e,_h)}}function rt(t){let e=En(t,At);if(e.schema!==Pt){if(e.schema===Wt||e.schema===zt){let o=e.schema===Wt?Rn(e):Cn(e);throw new bn(o.name,o.schema)}throw new Jt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=kn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Jt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=kn(e.revision,"Native revision"),r=Ec(e,TS),a=DS(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:n,verification_protocol:FS(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Nc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Nc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Nc(e.partial_allowance,"Native partial_allowance","allowances")}}function BS(t){let e=En(t,At);if(e.schema===Wt){let r=Rn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema===zt){let r=Cn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema!==Pt){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Jt(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=kn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Jt(e.schema,i).message};let n=rt(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function bc(t){let e=rt(t);return{schema:e.schema,minimum_runtime_version:e.minimum_runtime_version,revision:e.revision,verification_protocol:e.verification_protocol,name:e.name,language:e.language,phase:e.phase,brief:e.brief,approval:e.approval,approved_contract_hash:e.approved_contract_hash??null,spec_changes:e.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:e.verification_result,verification_report:e.verification_report,implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Y(t,e){kc(e);let i=nt.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Pn(t,e){let i=nt.join(Y(t,e),"runtime","schema-migration.json");await q(t.nativeRoot,i);try{return await Th.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Hh(t,e){let i=nt.join(Y(t,e),"runtime","checkpoint-journal.json");await q(t.nativeRoot,i);try{return await Th.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var qS=256*1024;async function Mh(t,e=nt.dirname(t)){let i=nt.relative(e,t).split(nt.sep).join("/"),n=await Ie({root:e,ref:i,maxBytes:qS}),r=(0,wa.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function VS(t,e){let i=nt.join(Y(t,e),At);await q(t.nativeRoot,i);let n=BS(await Mh(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Pn(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await zS(t,n.state),n)}async function zS(t,e){if(await bh(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function Ne(t,e){let i=await VS(t,e);if(i.status==="migration-required")throw new bn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Jt(i.schema,i.minimumRuntimeVersion);return i.state}async function WS(t,e,i){let n={...e,schema:Pt,minimum_runtime_version:3,revision:i+1},r=await Zd({expectedRevision:i,next:n,read:async()=>{let a=rt(await Mh(t));if(a.name!==e.name)throw new Error(`Native change file/name mismatch: ${e.name}`);return a},write:a=>Ze(t,(0,wa.stringify)(bc(a))),equals:(a,o)=>JSON.stringify(bc(a))===JSON.stringify(bc(o)),conflict:a=>new Sn(e.name,i,a)});return Object.assign(e,r),r}async function ya(t,e,i,n){if(await ln(t.projectRoot),await Pn(t,e.name))throw new bn(e.name,e.schema);if(!n?.allowPendingCheckpointRecovery&&await Hh(t,e.name))throw new Error(`Native progress checkpoint recovery is required for ${e.name} before another state write`);if((await Ne(t,e.name)).verification_protocol!==e.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await va(t,e.name);let a=nt.join(Y(t,e.name),At);return await q(t.nativeRoot,a),WS(a,e,i)}import{promises as rE}from"fs";import An from"path";var JS=/\b(Bearer|Basic)\s+[^\s"']+/giu,KS=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,GS=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,US=/\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,YS=/("(?:[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,XS=/(["'])((?:[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,QS=/\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 Ce(t){return t.replace(JS,"$1 [REDACTED]").replace(KS,"[REDACTED PRIVATE KEY]").replace(GS,"$1[REDACTED]@").replace(US,"[REDACTED TOKEN]").replace(YS,'$1"[REDACTED]"').replace(XS,"$1$2$1$3$4[REDACTED]$4").replace(QS,"$1$2[REDACTED]")}var Na={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},gi=/^[a-f0-9]{64}$/u;function ba(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Sa(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));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 xt(t,e,i=2e3){if(typeof t!="string"||t.length===0||t.length>i)throw new Error(`${e} must be a non-empty string of at most ${i} characters`);return t}function Lh(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Rc(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ZS(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||An.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=An.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function ek(t,e){return An.join(Y(t,e),"runtime","checkpoints","progress.json")}function Cc(t,e){return An.join(Y(t,e),"runtime","checkpoint-journal.json")}function Dh(t,e,i){if(!gi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return An.join(Y(t,e),"runtime","checkpoints","manifests",`${i}.json`)}function tk(t){if(!gi.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function Fh(t,e,i){let n=await tt({root:t,file:e,maxBytes:Na.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function ik(t,e){let i=ba(t,`checkpoint manifest artifact ${e}`);Sa(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let n=ZS(xt(i.path,`checkpoint artifact ${e} path`,4096)),r=We(n);if(r)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!gi.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:n,hash:i.hash,size:Rc(i.size,`checkpoint artifact ${e} size`)}}function ka(t,e){let i=ba(t,"Native checkpoint manifest");if(Sa(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!==e)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>Na.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(ik),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=Rc(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>Na.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:e,artifacts:n,totalBytes:a}}function Pc(t){return G(JSON.stringify(ka(t,t.change)))}function Bh(t,e){let i=ba(t,"Native progress checkpoint");if(Sa(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!==e)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=Lh(i.previousRevision,"Native checkpoint previousRevision"),a=Lh(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=xt(i.manifestHash,"Native checkpoint manifestHash",64);if(!gi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=tk(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=xt(i.inputHash,"Native checkpoint inputHash",64);if(!gi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=xt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Rc(i.artifactCount,"Native checkpoint artifactCount");if(u>Na.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let f=xt(i.summary,"Native checkpoint summary"),d=xt(i.nextAction,"Native checkpoint nextAction");if(Ce(f)!==f||Ce(d)!==d)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:xt(i.id,"Native checkpoint id",128),change:e,phase:n,previousRevision:r,stateRevision:a,summary:f,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function nk(t,e){let i=ba(t,"Native checkpoint journal");if(Sa(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!==e)throw new Error("Native checkpoint journal change mismatch");let n=rt(i.previousState),r=rt(i.nextState),a=Bh(i.checkpoint,e),o=ka(i.manifest,e),s=xt(i.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!gi.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!==e||r.name!==e||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==Pc(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:e,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function qh(t,e,i){let n=Dh(t,e,i);await q(t.nativeRoot,n);let r=await Fh(t.nativeRoot,n,"Native checkpoint manifest"),a=ka(r,e);if(Ac(t,a),Pc(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Vh(t,e){let i=Cc(t,e);await q(t.nativeRoot,i);try{let n=nk(await Fh(t.nativeRoot,i,"Native checkpoint journal"),e);return Ac(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function zh(t,e,i,n){let r=ka(i,e);Ac(t,r);let a=Pc(r),o=Dh(t,e,a);await q(t.nativeRoot,o);try{let s=await qh(t,e,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 Oe(o,r,{containedRoot:t.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Ac(t,e){for(let i of e.artifacts){let n=wd(t,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Wh(t,e){let i=Bh(e,e.change),n=await qh(t,i.change,i.manifestHash),r=G(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=ek(t,e.change);await q(t.nativeRoot,a),await Oe(a,i,{containedRoot:t.nativeRoot})}import{promises as qk}from"fs";import Vk from"path";import{isDeepStrictEqual as Yc}from"util";import{createHash as rk}from"crypto";function Le(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function ak(t,e){e.has(t)&&Le("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;n<t.length;n+=1)Object.prototype.hasOwnProperty.call(t,n)||Le("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Le("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Le("symbol properties are not supported"),`[${t.map(n=>xc(n,e)).join(",")}]`}finally{e.delete(t)}}function ok(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Le("only plain objects are supported"),e.has(t)&&Le("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Le("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Le("accessor properties are not supported"),`${JSON.stringify(o)}:${xc(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function xc(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Le("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?ak(t,e):ok(t,e);case"bigint":case"function":case"symbol":case"undefined":return Le(`${typeof t} values are not supported`)}return Le("unsupported value type")}function Ea(t){return xc(t,new Set)}function W(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return rk("sha256").update(`${t}
|
|
156
|
-
${Ea(e)}`).digest("hex")}var Tc={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var
|
|
151
|
+
${Buffer.byteLength(n)}:${n}`)}function uc(t){return t.reason==="git-enumeration-limit"||t.reason==="git-selection-changed"||t.reason==="physical-enumeration-limit"||t.reason==="physical-selection-changed"}function sh(t){for(let e=t.length-1;e>=0;e-=1){let i=t[e];if(!uc(i))return t.splice(e,1),i}return null}function Et(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function eS(t,e,i,n){if(!_(n))return{status:"budget-exhausted"};let r;try{r=await U.open(t,"r")}catch(c){if(!_(n))return{status:"budget-exhausted"};throw c}if(!_(n))return await r.close(),{status:"budget-exhausted"};let a=fa("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,e+1)),s=0;try{if(!_(n))return{status:"budget-exhausted"};let c=await r.stat();if(!_(n))return{status:"budget-exhausted"};if(!c.isFile()||!Et(i,c))return{status:"changed"};for(;;){if(!_(n))return{status:"budget-exhausted"};let l=e+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 f=await r.stat();return _(n)?!f.isFile()||!Et(c,f)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:f}:{status:"budget-exhausted"}}if(s+u.bytesRead>e)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await r.close()}}function Ee(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Re(t,e,i){let n=Object.keys(t).find(r=>!e.has(r));if(n)throw new Error(`${i} contains unknown field: ${n}`)}function fi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Je(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function yh(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let i=V.posix.normalize(t);if(i!==t||V.posix.isAbsolute(t)||i===".."||i.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function tS(t,e){let i=Ee(t,`Native snapshot entry ${e}`);Re(i,kb,`Native snapshot entry ${e}`);let n=yh(i.path,`Native snapshot entry ${e} path`);if(typeof i.hash!="string"||!da.test(i.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let r={path:n,hash:i.hash,size:Je(i.size,`Native snapshot entry ${e} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!dh.test(i.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);r.gitObjectId=i.gitObjectId}return r}function iS(t,e){let i=Ee(t,`Native snapshot omission ${e}`);if(Re(i,Eb,`Native snapshot omission ${e}`),!Pb.has(i.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Ab.has(i.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:yh(i.path,`Native snapshot omission ${e} path`),size:i.size===null?null:Je(i.size,`Native snapshot omission ${e} size`),type:i.type,reason:i.reason}}function nS(t){let e=Ee(t,"Native snapshot omission overflow");if(Re(e,Rb,"Native snapshot omission overflow"),typeof e.hash!="string"||!da.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:e.hash,count:fi(e.count,"Native snapshot omission overflow count")}}function ui(t,e){let i=Ee(t,e);if(Re(i,Nb,e),typeof i.hash!="string"||!da.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Je(i.recordCount,`${e} recordCount`),r=Je(i.storedRecordCount,`${e} storedRecordCount`),a=Je(i.stdoutBytes,`${e} stdoutBytes`);if(r>n||!i.overflow&&r!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,recordCount:n,storedRecordCount:r,stdoutBytes:a,overflow:i.overflow}}function ch(t){let e=Ee(t,"Native Git selection evidence");if(Re(e,yb,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ui(e.stageBefore,"Native Git selection stageBefore"),n=ui(e.combined,"Native Git selection combined"),r=ui(e.stageAfter,"Native Git selection stageAfter"),a=ui(e.finalStageBefore,"Native Git selection finalStageBefore"),o=ui(e.finalCombined,"Native Git selection finalCombined"),s=ui(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,n,r,a,o,s].some(f=>f.overflow),l=!Rt(i,r)||!Rt(r,a)||!Rt(n,o)||!Rt(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(e.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 lh(t,e){let i=Ee(t,e);if(Re(i,Sb,e),typeof i.hash!="string"||!da.test(i.hash))throw new Error(`${e} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${e} flags are invalid`);let n=Je(i.visitedNodeCount,`${e} visitedNodeCount`),r=Je(i.recordCount,`${e} recordCount`),a=Je(i.storedRecordCount,`${e} storedRecordCount`),o=Je(i.encodedBytes,`${e} encodedBytes`);if(a>r||!i.overflow&&a!==r)throw new Error(`${e} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:n,recordCount:r,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function rS(t){let e=Ee(t,"Native physical selection evidence");if(Re(e,bb,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=lh(e.before,"Native physical selection before"),n=lh(e.after,"Native physical selection after"),r=i.overflow||n.overflow,a=i.unstable||n.unstable||!vh(i,n);if(!r&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=r&&a?"overflow-and-changed":r?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:n}}function hn(t){let e=Ee(t,"Native content snapshot manifest");if(Re(e,pb,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Cb.has(e.origin))throw new Error("Native content snapshot origin is invalid");let i;if(e.capture!==void 0){let g=Ee(e.capture,"Native content snapshot capture");if(Re(g,gb,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let b=g.gitSelection===void 0?void 0:ch(g.gitSelection),y=g.physicalSelection===void 0?void 0:rS(g.physicalSelection),R=null;if(g.projection!==void 0){let O=Ee(g.projection,"Native content snapshot projection");if(Re(O,wb,"Native content snapshot projection"),O.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");R={provider:"git",...O.selection===void 0?{}:{selection:ch(O.selection)}}}if(g.provider==="git"){if(y||R)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...b?{gitSelection:b}:{}}}else{if(b)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(y&&R)throw new Error("Native physical-tree capture cannot combine selection and projection");i=R?{provider:"physical-tree",projection:R}:{provider:"physical-tree",...y?{physicalSelection:y}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Ee(e.limits,"Native content snapshot limits");Re(n,mb,"Native content snapshot limits");let r={maxFiles:fi(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:fi(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:fi(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:fi(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:fi(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Ee(e.policy,"Native snapshot policy");if(Re(g,vb,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=wh({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(tS),s=e.omitted.map(iS),c=Je(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:nS(e.omissionOverflow);if(o.length>r.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>r.maxFileBytes)||o.reduce((g,b)=>g+b.size,0)>r.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>fh||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(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.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!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let E=i?.physicalSelection,k=E?.status==="overflow"||E?.status==="overflow-and-changed",N=E?.status==="changed"||E?.status==="overflow-and-changed";if(k!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let S={schema:"comet.native.content-snapshot.v1",origin:e.origin,...i?{capture:i}:{},createdAt:e.createdAt,complete:e.complete,limits:r,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(gh(S)>r.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return S}function aS(t,e){if(!hb.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=V.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return V.join(i,"runtime","baseline-manifest.json")}async function Nh(t,e={}){let i={maxFiles:e.limits?.maxFiles??ca.maxFiles,maxFileBytes:e.limits?.maxFileBytes??ca.maxFileBytes,maxTotalBytes:e.limits?.maxTotalBytes??ca.maxTotalBytes,maxManifestBytes:e.limits?.maxManifestBytes??ca.maxManifestBytes,...e.limits?.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},n=wh(e.policy),r=jb({...e,deadlineMs:e.deadlineMs??i.maxDurationMs}),a=Mb(e.gitSelectionLimits),o=$b(e.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=V.resolve(t.projectRoot),c=await U.realpath(s),l=V.resolve(t.nativeRoot),u=await U.realpath(l),f=V.resolve(t.configFile),d=V.join(s,".comet","current-change.json"),p=Yb(s,e.denylist??[]),m=[],h=[],v=new Map,w=new Map,E=0,k=0,N=G("comet.native.snapshot-omission-overflow.v1"),S=0,g=!1,b=null,y=P=>{k+=1,N=cc(N,"omission",P)},R=P=>{if(E+=1,h.length<fh){h.push(P);return}if(uc(P)){let A=sh(h);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(A),h.push(P);return}y(P)},O=P=>{E+=P.count,k+=P.count,N=cc(N,"git-selection",{source:"git-selection",...P})},B=P=>{k+=1,N=cc(N,"manifest-entry",{reason:"manifest-size",entry:P})},H=async(P,A)=>{m.push(P),S+=P.size,v.set(P.path,A),g||(g=!0,await e.gitSelectionHooks?.afterFirstEntryCaptured?.(P.path))},D=(P,A)=>{let T=m.findIndex(X=>X.path===P);if(T<0)return;let[$]=m.splice(T,1);S-=$.size,v.delete(P),R(A)},J=async(P,A,T,$)=>{if(!T.isFile()||T.isSymbolicLink()||!_(r))return;let X;try{X=await U.realpath(P)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:T.size,type:"file",reason:Z(I)?"changed-during-read":"unreadable"});return}if(!_(r)||!ae(c,X)||Ct(u,X))return;if(m.length>=i.maxFiles){R({path:A,size:T.size,type:"file",reason:"file-count"});return}if(T.size>i.maxFileBytes){R({path:A,size:T.size,type:"file",reason:"file-size"});return}if(S+T.size>i.maxTotalBytes){R({path:A,size:T.size,type:"file",reason:"total-size"});return}let L,j,x;try{if(L=await eS(X,T.size,T,r),L.status==="budget-exhausted"||!_(r))return;if(L.status==="changed"){R({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!_(r)||(x=await U.realpath(P),!_(r)))return;j=await U.lstat(P)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:T.size,type:"file",reason:Z(I)?"changed-during-read":"unreadable"});return}if(_(r)){if(L.bytes!==T.size||x!==X||!Et(T,L.finalStat)||!Et(L.finalStat,j)||!j.isFile()||j.isSymbolicLink()||j.size!==T.size||j.mtimeMs!==T.mtimeMs||j.ctimeMs!==T.ctimeMs){R({path:A,size:j.isFile()?j.size:null,type:j.isFile()?"file":"other",reason:"changed-during-read"});return}_(r)&&await H({path:A,hash:L.hash,size:j.size,type:"file",...$===void 0?{}:{gitObjectId:$}},{kind:"file",target:P,realTarget:X,stat:j})}},Be=async(P,A,T)=>{if(!_(r))return;let $,X,L;try{if($=await U.readlink(P,{encoding:"buffer"}),!_(r)||(L=await U.lstat(P),!_(r)))return;X=await U.readlink(P,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;R({path:A,size:null,type:"other",reason:Z(I)?"changed-during-read":"unreadable"});return}if(!_(r))return;if(!L.isSymbolicLink()||!Et(T,L)||L.mtimeMs!==T.mtimeMs||L.ctimeMs!==T.ctimeMs||!$.equals(X)){R({path:A,size:null,type:"other",reason:"changed-during-read"});return}let j=$.byteLength;if(m.length>=i.maxFiles){R({path:A,size:j,type:"other",reason:"file-count"});return}if(j>i.maxFileBytes){R({path:A,size:j,type:"other",reason:"file-size"});return}if(S+j>i.maxTotalBytes){R({path:A,size:j,type:"other",reason:"total-size"});return}let x=fa("sha256").update("symlink\0").update($).digest("hex");_(r)&&await H({path:A,hash:x,size:j,type:"file"},{kind:"symlink",target:P,rawTarget:$,stat:L})},qe=async()=>{for(let[P,A]of[...v]){if(!_(r))return;if(A.kind==="file"){let j,x;try{if(j=await U.realpath(A.target),!_(r))return;x=await U.lstat(A.target)}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;D(P,{path:P,size:null,type:"file",reason:ee(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(j!==A.realTarget||!x.isFile()||x.isSymbolicLink()||!Et(A.stat,x)||x.size!==A.stat.size||x.mtimeMs!==A.stat.mtimeMs||x.ctimeMs!==A.stat.ctimeMs)&&D(P,{path:P,size:x.isFile()?x.size:null,type:x.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let j,x;try{if(j=await U.lstat(A.target),!_(r))return;x=await U.readlink(A.target,{encoding:"buffer"})}catch(I){if(!_(r))return;if(!ee(I)&&!Z(I))throw I;D(P,{path:P,size:null,type:"other",reason:ee(I)?"unreadable":"changed-during-read"});continue}if(!_(r))return;(!j.isSymbolicLink()||!Et(A.stat,j)||j.mtimeMs!==A.stat.mtimeMs||j.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(x))&&D(P,{path:P,size:null,type:"other",reason:"changed-during-read"});continue}let T,$;try{if(T=await U.realpath(A.target),!_(r))return;$=await U.lstat(A.target)}catch{if(!_(r))return;D(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;if(!(T===A.realTarget&&$.isDirectory()&&!$.isSymbolicLink()&&Et(A.stat,$)&&ae(c,T)&&!Ct(u,T))){D(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"});continue}let L;try{if(!_(r))return;L=await rh(r,T)}catch(j){if(dn(j))throw j;D(P,{path:P,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!_(r))return;L.dirty?D(P,{path:P,size:null,type:"directory",reason:"gitlink-dirty"}):L.hash!==A.hash&&D(P,{path:P,size:null,type:"directory",reason:"gitlink-changed"})}for(let[P,A]of w){if(!_(r))return;try{let T=await U.lstat(A);if(!_(r))return;R({path:P,size:T.isFile()?T.size:null,type:T.isFile()?"file":T.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(T){if(!_(r))return;if(Z(T))continue;if(!ee(T))throw T;R({path:P,size:null,type:"file",reason:"unreadable"})}}},me=await Bb(r,s,a,e.gitSelectionHooks);if(me===null){let P=await ih({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o,hooks:e.physicalSelectionHooks});await e.physicalSelectionHooks?.afterInitialSelection?.();for(let $ of P.records){if($.type!=="file"&&$.type!=="symlink"||v.has($.path))continue;if(Me(r)<1)break;if(!oh(n,$.path,r))continue;if(Me(r)<1)break;let X=V.resolve(s,...$.path.split("/")),L;try{L=await U.lstat(X)}catch(j){if(!_(r))break;if(!ee(j)&&!Z(j))throw j;R({path:$.path,size:null,type:"file",reason:Z(j)?"changed-during-read":"unreadable"});continue}if(Me(r)<1)break;if($.type==="symlink"&&L.isSymbolicLink()){if(await Be(X,$.path,L),Me(r)<1)break;continue}if($.type!=="file"||!L.isFile()||L.isSymbolicLink()){R({path:$.path,size:L.isFile()?L.size:null,type:L.isDirectory()?"directory":L.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await J(X,$.path,L),Me(r)<1)break}Me(r)>=1&&await qe();let A=await ih({execution:r,paths:t,physicalProjectRoot:c,physicalNativeRoot:u,denylist:p,policy:n,limits:o}),T=Jb(P.evidence,A.evidence);b=T.evidence;for(let $ of[...P.omissions,...A.omissions,...T.omissions])h.some(X=>X.path===$.path&&X.reason===$.reason)||R($)}else{await e.gitSelectionHooks?.afterInitialSelection?.();let P=e.incrementalBaseline,A=new Map,T=!1;if(P){let x=hn(P);for(let I of x.entries)I.gitObjectId!==void 0&&A.set(I.path,I);T=A.size>0}let $=new Set,X=!0;try{let x=await la(r,s,["ls-files","--modified","-z"],lc);for(let I of x.toString("utf8").split("\0")){let ie=ua(I);ie!==null&&$.add(ie)}}catch{T=!1,X=!1,A.clear()}let L=new Set,j=new Set;for(let x of Kb(me)){if(v.has(x)||!Gb(t,x))continue;if(Me(r)<1)break;if(!oh(n,x,r))continue;if(Me(r)<1)break;let I=V.resolve(s,...x.split("/"));if(I===f||I===d||p.some(ge=>Ct(ge,I)))continue;if(me.gitlinks.has(x)){if(m.length>=i.maxFiles){R({path:x,size:0,type:"file",reason:"file-count"});continue}let ge,Dn;try{[ge,Dn]=await Promise.all([U.realpath(I),U.lstat(I)])}catch{R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Dn.isSymbolicLink()||!Dn.isDirectory()||!ae(c,ge)||Ct(u,ge)){R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Ut=await rh(r,ge);if(Ut.dirty){R({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await H({path:x,hash:Ut.hash,size:0,type:"file"},{kind:"gitlink",target:I,realTarget:ge,stat:Dn,hash:Ut.hash})}catch(Ut){if(dn(Ut))throw Ut;R({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ie;try{ie=await U.lstat(I)}catch(ge){if(Z(ge)&&me.tracked.has(x)){w.set(x,I);continue}if(!ee(ge)&&!Z(ge))throw ge;R({path:x,size:null,type:"file",reason:Z(ge)?"changed-during-read":"unreadable"});continue}if(ie.isSymbolicLink()){await Be(I,x,ie);continue}if(!ie.isFile()){me.nestedRepositories.has(x)||R({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Pe=me.trackedObjectIds.get(x),ve=Pe?A.get(x):void 0;if(T&&ve?.gitObjectId!==void 0&&ve.gitObjectId===Pe&&!$.has(x)){if(m.length>=i.maxFiles){R({path:x,size:ve.size,type:"file",reason:"file-count"});continue}if(ve.size>i.maxFileBytes){R({path:x,size:ve.size,type:"file",reason:"file-size"});continue}if(S+ve.size>i.maxTotalBytes){R({path:x,size:ve.size,type:"file",reason:"total-size"});continue}m.push({...ve}),S+=ve.size,L.add(x);continue}let Rl=X&&!$.has(x)?Pe:void 0;await J(I,x,ie,Rl),Rl!==void 0&&j.add(x)}if(await qe(),await e.gitSelectionHooks?.afterContentRevalidation?.(),await Vb(r,s,a,me,e.gitSelectionHooks?.outputChunkBytes),L.size>0||T&&j.size>0){let x=await la(r,s,["ls-files","--modified","-z"],lc),I=new Set;for(let ie of x.toString("utf8").split("\0")){let Pe=ua(ie);Pe!==null&&I.add(Pe)}for(let ie of L){if(!I.has(ie))continue;let Pe=m.find(ve=>ve.path===ie);D(ie,{path:ie,size:Pe?.size??null,type:"file",reason:"changed-during-read"})}for(let ie of j){if(!I.has(ie))continue;let Pe=m.find(ve=>ve.path===ie);Pe&&delete Pe.gitObjectId}}for(let x of me.omissions)R(x);me.overflow&&O(me.overflow)}m.sort((P,A)=>P.path.localeCompare(A.path,"en")),h.sort((P,A)=>P.path.localeCompare(A.path,"en"));let hm=me===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...me.evidence?{gitSelection:me.evidence}:{}},El=()=>({schema:"comet.native.content-snapshot.v1",origin:e.origin??"explicit",capture:hm,createdAt:(e.now??new Date).toISOString(),complete:E===0,limits:i,...n?{policy:n.manifest}:{},entries:m,omitted:h,omittedCount:E,...k>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:k}}:{}}),Ya=El();for(;gh(Ya)>i.maxManifestBytes;){if(h.filter(A=>!uc(A)).length>0){let A=Math.max(1,Math.ceil(h.length/4));for(let T=0;T<A;T+=1){let $=sh(h);if($===null)break;y($)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let T of m.splice(-A))E+=1,B(T)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Ya=El()}return Ya}async function dc(t,e,i={}){let r=(await qt(t.projectRoot))?.native.snapshot??Us;return Nh(t,{...i,policy:e.policy,incrementalBaseline:e,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 bh(t,e){let i=aS(t,e);await q(t.nativeRoot,i);try{let n=await Wd({root:t.nativeRoot,file:i,maxBytes:db,label:"Native baseline snapshot manifest"});return hn(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as SS}from"crypto";import wc from"path";var Ke=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{constants as pa,promises as le}from"node:fs";import ye from"node:path";import{TextDecoder as vS}from"node:util";import dS from"path";var Sh=(t,e)=>{let i=t[e];return i==null?null:String(i)};function mn(t,e){let i=t[e];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return i}function pn(t,e){let i=mn(t,e);if(dS.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return i}function hS(t){let e=t.run_retries??"{}",i;try{i=typeof e=="string"?JSON.parse(e):e}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 kh(t){if(!t.run_id)return null;let e=mn(t,"run_id"),i=mn(t,"skill"),n=mn(t,"skill_version"),r=mn(t,"skill_hash"),a=pn(t,"pending_ref"),o=pn(t,"trajectory_ref"),s=pn(t,"context_ref"),c=pn(t,"artifacts_ref"),l=pn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:i,skillVersion:n,skillHash:r,orchestration:t.orchestration,currentStep:Sh(t,"current_step"),iteration:u,pending:Sh(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:hS(t)}}var Fx=256*1024;var pS=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function mS(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)},i=kh(e);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Run state: stored value must be an object");let e=t,i=Object.keys(e).find(n=>!pS.has(n));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(e.currentStep!==null&&(typeof e.currentStep!="string"||e.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(e.pending!==null&&(typeof e.pending!="string"||e.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!e.retries||typeof e.retries!="object"||Array.isArray(e.retries))throw new Error("Invalid Run state: retries must be an object");return mS(e)}var we={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 gn(t,e){let i=ye.relative(t,e);return i===""||!ye.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${ye.sep}`)}function Rh(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function vn(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}function gS(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function hi(t,e,i){let n=Ke[e];if(i!==void 0&&i!==n)throw new Error(`Native Run ${e} ref must be ${n}`);let r=ye.resolve(t),a=ye.resolve(r,...n.split("/"));if(!gn(r,a))throw new Error("Native Run path must stay inside its change");return a}async function Eh(t){let e=await le.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${t}`);return{path:t,realPath:await le.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function hc(t,e){let i=ye.resolve(t),n=ye.resolve(e);if(!gn(i,n))throw new Error("Native Run path is outside its change");let r=[await Eh(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 Eh(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!gn(r[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);r.push(s)}return r}async function ma(t){for(let e of t){let i=await le.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!gS(e,i)||await le.realpath(e.path)!==e.realPath)throw new Error(`Native Run parent changed during I/O: ${e.path}`)}}async function wS(t,e,i){let n=[],r=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-r,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(r+=s,r>e)throw new Error(`${i} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,r)}async function wn(t,e,i,n,r){let a=await hc(t,ye.dirname(e));if(!a)return null;await r?.afterParentChainCaptured?.();let o;try{o=await le.lstat(e)}catch(f){if(f.code==="ENOENT")return null;throw f}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=Rh(o),c=await le.realpath(e);if(!gn(a[0].realPath,c))throw new Error(`${n} resolves outside its change`);let l=process.platform==="win32"?pa.O_RDONLY:pa.O_RDONLY|pa.O_NOFOLLOW|pa.O_NONBLOCK,u;try{u=await le.open(e,l)}catch(f){throw new Error(`${n} changed while opening`,{cause:f})}try{let[f,d,p]=await Promise.all([u.stat(),le.lstat(e),le.realpath(e)]);if(await ma(a),!f.isFile()||!d.isFile()||d.isSymbolicLink()||p!==c||!vn(s,f)||!vn(s,d))throw new Error(`${n} changed while opening`);await r?.afterOpen?.();let m=await wS(u,i,n);await r?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([u.stat(),le.lstat(e),le.realpath(e)]);if(await ma(a),!v.isFile()||v.isSymbolicLink()||w!==c||!vn(s,h)||!vn(s,v))throw new Error(`${n} changed while reading`);let E;try{E=new vS("utf-8",{fatal:!0}).decode(m)}catch(k){throw new Error(`${n} is not valid UTF-8`,{cause:k})}return{text:E,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function yS(t,e,i){let n=await hc(t,ye.dirname(e));if(!n)return{exists:!1};let r;try{r=await le.lstat(e)}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 le.realpath(e);if(!gn(n[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await ma(n),{exists:!0,identity:Rh(r),realPath:a}}async function NS(t,e,i,n){let r=await hc(t,ye.dirname(e));if(!r){if(!i.exists)return;throw new Error(`${n} parent changed before commit`)}let a;try{a=await le.lstat(e)}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()||!vn(i.identity,a)||await le.realpath(e)!==i.realPath)throw new Error(`${n} changed before commit`);await ma(r)}async function pc(t){if(Buffer.byteLength(t.content,"utf8")>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);let i=t.expected??await yS(t.changeDir,t.file,t.label);if(i.exists&&i.identity.size>t.maxBytes)throw new Error(`${t.label} exceeds ${t.maxBytes} bytes`);await Ze(t.file,t.content,{containedRoot:t.changeDir,beforeCommit:async()=>{await t.hooks?.beforeCommit?.(),await NS(t.changeDir,t.file,i,t.label)}});let n=await wn(t.changeDir,t.file,t.maxBytes,t.label);if(!n||n.text!==t.content)throw new Error(`${t.label} commit could not be verified`)}function bS(t,e){try{return JSON.parse(t)}catch(i){throw new Error(`${e} contains invalid JSON`,{cause:i})}}function Ch(t){return`${JSON.stringify(t,null,2)}
|
|
152
|
+
`}function mc(t){return ha(t)}async function yn(t,e){let i=hi(t,"stateRef"),n=await wn(t,i,we.runStateBytes,"Native Run state",e);return n?ha(bS(n.text,"Native Run state")):null}async function vc(t,e,i){let n=ha(e);await pc({changeDir:t,file:hi(t,"stateRef"),content:Ch(n),maxBytes:we.runStateBytes,label:"Native Run state",hooks:i})}async function pi(t,e,i){let n=hi(t,"trajectoryRef",e),r=await wn(t,n,we.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>we.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${we.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 Ph(t,e,i){return(await wn(t,hi(t,"trajectoryRef",e),we.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function Ah(t,e,i,n){let r=hi(t,"trajectoryRef",e),a=`${JSON.stringify(i)}
|
|
153
|
+
`;if(Buffer.byteLength(a,"utf8")>we.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${we.trajectoryEventBytes} bytes`);let o=await wn(t,r,we.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=we.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${we.trajectoryEvents} events`);await pc({changeDir:t,file:r,content:`${o?.text??""}${a}`,maxBytes:we.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:n})}async function xh(t,e,i,n){await pc({changeDir:t,file:hi(t,"checkpointRef",e),content:Ch(i),maxBytes:we.checkpointBytes,label:"Native Run checkpoint",hooks:n})}var kS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yc=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 gc(t){return SS("sha256").update(t).digest("hex")}function ES(t,e){if(!kS.test(e))throw new Error(`Invalid Native change name: ${e}`);let i=wc.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return wc.join(i,"runtime","trajectory.jsonl")}function RS(t){let e=t.split(/\n/u),i=0;for(let n=0;n<e.length;n+=1){let r=e[n].endsWith("\r")?e[n].slice(0,-1):e[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 CS(t,e){if(/Unexpected end|Unterminated string/iu.test(t.message))return!0;let i=/position (\d+)/iu.exec(t.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,e.length-1)}function PS(t,e){let i=e.lastIndexOf(10),n=e.subarray(0,i+1),r=RS(n.toString("utf8"));if(r.status==="invalid")return{status:"invalid",file:t,line:r.line,message:r.message};if(i===e.length-1)return{status:"clean",file:t};let a=e.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([e,Buffer.from(`
|
|
154
|
+
`)])}catch(f){if(!CS(f,o))return{status:"invalid",file:t,line:s,message:f.message};c="incomplete-json",l=n}return{inspection:{status:"repairable",file:t,reason:c,line:s,originalHash:gc(e),targetHash:gc(l),tailHash:gc(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function AS(t,e){let i=ES(t,e);await q(t.nativeRoot,i);let n=wc.join(t.changesDir,e),r=await Ph(n,Ke.trajectoryRef);return r===null?{status:"clean",file:i}:PS(i,Buffer.from(r))}async function xS(t,e){let i=await AS(t,e);return"inspection"in i?i.inspection:i}async function va(t,e){let i=await xS(t,e);if(i.status!=="clean")throw new yc(i)}var dT=16*1024;var Pt="comet.native.v3",zt="comet.native.v2",Wt="comet.native.v1",mi="comet.native.transition.v3",vi="comet.native.transition.v2",Nn="comet.native.transition.v1";var Ih=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],TS=new Set(Ih),_h=new Set([...Ih,"minimum_runtime_version","revision"]),IS=new Set([..._h,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),_S=new Set(["capability","operation","source","base_hash"]),OS=new Set(["shape","build","verify","archive"]),jS=new Set(["implicit","confirmed"]),$S=new Set(["pending","pass","fail"]),At="comet-state.yaml",Sc=/^[a-f0-9]{64}$/u,Oh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,bn=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"},Jt=class extends Error{constructor(i,n){super(i!==Pt||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"},Sn=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"},ga=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"},IT=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
|
|
155
|
+
`);function En(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function jh(t,e,i){let n=Object.keys(t).filter(r=>!e.has(r));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`)}function kc(t){if(!Oh.test(t))throw new Error(`Invalid Native change name: ${t}`)}function MS(t){if(!Oh.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function $h(t,e){if(t.length===0||nt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function LS(t,e){let i=En(t,`spec_changes[${e}]`);if(jh(i,_S,`spec_changes[${e}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(MS(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"&&$h(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"||!Sc.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"||!Sc.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 DS(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Ec(t,e){if(jh(t,e,At),typeof t.name!="string")throw new Error("Native change name is required");if(kc(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!OS.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!jS.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let i=t.spec_changes.map(LS),n=i.map(r=>r.capability).filter((r,a,o)=>o.indexOf(r)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof t.verification_result!="string"||!$S.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&$h(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!DS(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:i,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Rn(t){let e=En(t,At);if(e.schema!==Wt)throw new Error(`Expected ${Wt}`);return{schema:Wt,...Ec(e,TS)}}function kn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Nc(t,e,i){if(t===null)return null;let n=typeof t=="string"?HS.exec(t):null;if(!n||n[1]!==i)throw new Error(`${e} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return t}function FS(t){if(t==null)return null;if(typeof t!="string"||!Sc.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function BS(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function Cn(t){let e=En(t,At);if(e.schema!==zt)throw new Error(`Expected ${zt}`);if(kn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${zt} minimum_runtime_version must be 2`);return{schema:zt,minimum_runtime_version:2,revision:kn(e.revision,"Native v2 revision"),...Ec(e,_h)}}function rt(t){let e=En(t,At);if(e.schema!==Pt){if(e.schema===Wt||e.schema===zt){let o=e.schema===Wt?Rn(e):Cn(e);throw new bn(o.name,o.schema)}throw new Jt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let i=kn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new Jt(e.schema,i);if(i!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=kn(e.revision,"Native revision"),r=Ec(e,IS),a=FS(e.approved_contract_hash);if(r.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pt,minimum_runtime_version:3,revision:n,verification_protocol:BS(e.verification_protocol),...r,approved_contract_hash:a,implementation_scope:Nc(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Nc(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Nc(e.partial_allowance,"Native partial_allowance","allowances")}}function qS(t){let e=En(t,At);if(e.schema===Wt){let r=Rn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:1,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema===zt){let r=Cn(e);return{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r,message:`Native change ${r.name} requires migration to ${Pt}`}}if(e.schema!==Pt){let r=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:r,state:null,message:new Jt(typeof e.schema=="string"?e.schema:"(missing)",r).message}}let i=kn(e.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:i,state:null,message:new Jt(e.schema,i).message};let n=rt(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function bc(t){let e=rt(t);return{schema:e.schema,minimum_runtime_version:e.minimum_runtime_version,revision:e.revision,verification_protocol:e.verification_protocol,name:e.name,language:e.language,phase:e.phase,brief:e.brief,approval:e.approval,approved_contract_hash:e.approved_contract_hash??null,spec_changes:e.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:e.verification_result,verification_report:e.verification_report,implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Y(t,e){kc(e);let i=nt.join(t.changesDir,e);if(!ae(t.changesDir,i))throw new Error("Native change path escaped");return i}async function Pn(t,e){let i=nt.join(Y(t,e),"runtime","schema-migration.json");await q(t.nativeRoot,i);try{return await Th.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Hh(t,e){let i=nt.join(Y(t,e),"runtime","checkpoint-journal.json");await q(t.nativeRoot,i);try{return await Th.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var VS=256*1024;async function Mh(t,e=nt.dirname(t)){let i=nt.relative(e,t).split(nt.sep).join("/"),n=await Ie({root:e,ref:i,maxBytes:VS}),r=(0,wa.parseDocument)(n.text,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${r.errors[0].message}`);return r.toJS()}async function zS(t,e){let i=nt.join(Y(t,e),At);await q(t.nativeRoot,i);let n=qS(await Mh(i,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Pn(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await WS(t,n.state),n)}async function WS(t,e){if(await bh(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function Ne(t,e){let i=await zS(t,e);if(i.status==="migration-required")throw new bn(e,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new Jt(i.schema,i.minimumRuntimeVersion);return i.state}async function JS(t,e,i){let n={...e,schema:Pt,minimum_runtime_version:3,revision:i+1},r=await Zd({expectedRevision:i,next:n,read:async()=>{let a=rt(await Mh(t));if(a.name!==e.name)throw new Error(`Native change file/name mismatch: ${e.name}`);return a},write:a=>Ze(t,(0,wa.stringify)(bc(a))),equals:(a,o)=>JSON.stringify(bc(a))===JSON.stringify(bc(o)),conflict:a=>new Sn(e.name,i,a)});return Object.assign(e,r),r}async function ya(t,e,i,n){if(await ln(t.projectRoot),await Pn(t,e.name))throw new bn(e.name,e.schema);if(!n?.allowPendingCheckpointRecovery&&await Hh(t,e.name))throw new Error(`Native progress checkpoint recovery is required for ${e.name} before another state write`);if((await Ne(t,e.name)).verification_protocol!==e.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await va(t,e.name);let a=nt.join(Y(t,e.name),At);return await q(t.nativeRoot,a),JS(a,e,i)}import{promises as aE}from"fs";import An from"path";var KS=/\b(Bearer|Basic)\s+[^\s"']+/giu,GS=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,US=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,YS=/\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,XS=/("(?:[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,QS=/(["'])((?:[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,ZS=/\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 Ce(t){return t.replace(KS,"$1 [REDACTED]").replace(GS,"[REDACTED PRIVATE KEY]").replace(US,"$1[REDACTED]@").replace(YS,"[REDACTED TOKEN]").replace(XS,'$1"[REDACTED]"').replace(QS,"$1$2$1$3$4[REDACTED]$4").replace(ZS,"$1$2[REDACTED]")}var Na={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},gi=/^[a-f0-9]{64}$/u;function ba(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Sa(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));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 xt(t,e,i=2e3){if(typeof t!="string"||t.length===0||t.length>i)throw new Error(`${e} must be a non-empty string of at most ${i} characters`);return t}function Lh(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Rc(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ek(t){let e=t.trim().replaceAll("\\","/");if(e.length===0||An.isAbsolute(e)||/^(?:[A-Za-z]:|~|\/)/u.test(e)||e.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${t}`);let i=An.posix.normalize(e);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${t}`);return i}function tk(t,e){return An.join(Y(t,e),"runtime","checkpoints","progress.json")}function Cc(t,e){return An.join(Y(t,e),"runtime","checkpoint-journal.json")}function Dh(t,e,i){if(!gi.test(i))throw new Error("Native checkpoint manifest hash is invalid");return An.join(Y(t,e),"runtime","checkpoints","manifests",`${i}.json`)}function ik(t){if(!gi.test(t))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${t}.json`}async function Fh(t,e,i){let n=await tt({root:t,file:e,maxBytes:Na.maxDocumentBytes,label:i});return JSON.parse(n.bytes.toString("utf8"))}function nk(t,e){let i=ba(t,`checkpoint manifest artifact ${e}`);Sa(i,["path","hash","size"],`checkpoint manifest artifact ${e}`);let n=ek(xt(i.path,`checkpoint artifact ${e} path`,4096)),r=We(n);if(r)throw new Error(`checkpoint artifact ${e} is excluded as sensitive (${r}): ${n}`);if(typeof i.hash!="string"||!gi.test(i.hash))throw new Error(`checkpoint artifact ${e} hash is invalid`);return{path:n,hash:i.hash,size:Rc(i.size,`checkpoint artifact ${e} size`)}}function ka(t,e){let i=ba(t,"Native checkpoint manifest");if(Sa(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!==e)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>Na.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let n=i.artifacts.map(nk),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=Rc(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>Na.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:e,artifacts:n,totalBytes:a}}function Pc(t){return G(JSON.stringify(ka(t,t.change)))}function Bh(t,e){let i=ba(t,"Native progress checkpoint");if(Sa(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!==e)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=Lh(i.previousRevision,"Native checkpoint previousRevision"),a=Lh(i.stateRevision,"Native checkpoint stateRevision");if(a!==r+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=xt(i.manifestHash,"Native checkpoint manifestHash",64);if(!gi.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=ik(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=xt(i.inputHash,"Native checkpoint inputHash",64);if(!gi.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=xt(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Rc(i.artifactCount,"Native checkpoint artifactCount");if(u>Na.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let f=xt(i.summary,"Native checkpoint summary"),d=xt(i.nextAction,"Native checkpoint nextAction");if(Ce(f)!==f||Ce(d)!==d)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:xt(i.id,"Native checkpoint id",128),change:e,phase:n,previousRevision:r,stateRevision:a,summary:f,nextAction:d,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function rk(t,e){let i=ba(t,"Native checkpoint journal");if(Sa(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!==e)throw new Error("Native checkpoint journal change mismatch");let n=rt(i.previousState),r=rt(i.nextState),a=Bh(i.checkpoint,e),o=ka(i.manifest,e),s=xt(i.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!gi.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!==e||r.name!==e||r.revision!==n.revision+1||a.previousRevision!==n.revision||a.stateRevision!==r.revision||a.phase!==r.phase||a.manifestHash!==Pc(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:e,inputHash:s,createdAt:a.createdAt,previousState:n,nextState:r,checkpoint:a,manifest:o}}async function qh(t,e,i){let n=Dh(t,e,i);await q(t.nativeRoot,n);let r=await Fh(t.nativeRoot,n,"Native checkpoint manifest"),a=ka(r,e);if(Ac(t,a),Pc(a)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return a}async function Vh(t,e){let i=Cc(t,e);await q(t.nativeRoot,i);try{let n=rk(await Fh(t.nativeRoot,i,"Native checkpoint journal"),e);return Ac(t,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function zh(t,e,i,n){let r=ka(i,e);Ac(t,r);let a=Pc(r),o=Dh(t,e,a);await q(t.nativeRoot,o);try{let s=await qh(t,e,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 Oe(o,r,{containedRoot:t.nativeRoot,beforeCommit:n?.beforeCommit}),a}function Ac(t,e){for(let i of e.artifacts){let n=wd(t,i.path);if(n)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${n}): ${i.path}`)}}async function Wh(t,e){let i=Bh(e,e.change),n=await qh(t,i.change,i.manifestHash),r=G(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=tk(t,e.change);await q(t.nativeRoot,a),await Oe(a,i,{containedRoot:t.nativeRoot})}import{promises as Vk}from"fs";import zk from"path";import{isDeepStrictEqual as Yc}from"util";import{createHash as ak}from"crypto";function Le(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function ok(t,e){e.has(t)&&Le("cyclic structures are not supported"),e.add(t);try{let i=Object.keys(t);for(let n=0;n<t.length;n+=1)Object.prototype.hasOwnProperty.call(t,n)||Le("sparse arrays are not supported");return(i.length!==t.length||i.some((n,r)=>n!==String(r)))&&Le("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Le("symbol properties are not supported"),`[${t.map(n=>xc(n,e)).join(",")}]`}finally{e.delete(t)}}function sk(t,e){let i=Object.getPrototypeOf(t);i!==Object.prototype&&i!==null&&Le("only plain objects are supported"),e.has(t)&&Le("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Le("symbol properties are not supported"),e.add(t);try{let n=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Le("accessor properties are not supported"),`${JSON.stringify(o)}:${xc(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function xc(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||Le("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?ok(t,e):sk(t,e);case"bigint":case"function":case"symbol":case"undefined":return Le(`${typeof t} values are not supported`)}return Le("unsupported value type")}function Ea(t){return xc(t,new Set)}function W(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return ak("sha256").update(`${t}
|
|
156
|
+
${Ea(e)}`).digest("hex")}var Tc={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var ck=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function lk(t,e){return t<e?-1:t>e?1:0}function uk(t,e,i,n){if(!Array.isArray(t)||t.length>i||!n&&t.length===0)throw new Error(`${e} exceeds its count boundary`);let r=t.map(a=>{if(typeof a!="string"||!ck.test(a))throw new Error(`${e} contains an invalid token: ${String(a)}`);return a});return[...new Set(r)].sort(lk)}function Jh(t=[]){return uk(t,"Native repair failed check IDs",Tc.maxFailedCheckIds,!0)}import cp from"node:path";import{createHash as Zh}from"node:crypto";import Kh from"path";var Ic="comet.native.implementation-scope.v2",ep="comet.native.content-snapshot-projection.v1",xn="comet.native.content-snapshot-projection.v1",tp="comet.native.implementation-scope.v2",fk="comet.native.unresolved-scope-id.v1",dk="comet.native.scope-detail-overflow.v1",hk="comet.native.snapshot-projection-overflow.v2",$c=/^[a-f0-9]{64}$/u,Gt=1024*1024,pk=128,mk=128;function oe(t,e){return t<e?-1:t>e?1:0}function _c(t){if(!$c.test(t))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${t}.json`}function vk(t,e){return t===e?0:t===null?-1:e===null?1:oe(t,e)}function It(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.endsWith("/")||/^[a-zA-Z]:/u.test(t))throw new Error(`${e} must be a normalized project-relative path`);let i=Kh.posix.normalize(t);if(i!==t||i==="."||i===".."||i.startsWith("../")||Kh.posix.isAbsolute(i))throw new Error(`${e} must stay inside the project root`);return t}function ip(t,e){return t==="."?t:It(t,e)}function wi(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative safe integer`);return t}function gk(t,e){if(t.type!=="file")throw new Error(`${e} must describe a file`);if(typeof t.hash!="string"||t.hash.length===0)throw new Error(`${e} hash must be non-empty`);return{path:It(t.path,`${e} path`),hash:t.hash,size:wi(t.size,`${e} size`),type:"file"}}function wk(t,e){return{path:ip(t.path,`${e} path`),size:t.size===null?null:wi(t.size,`${e} size`),type:t.type,reason:t.reason}}function yk(t,e){return oe(t.path,e.path)||oe(t.hash,e.hash)||t.size-e.size}function Nk(t,e){return oe(t.path,e.path)||oe(t.reason,e.reason)||oe(t.type,e.type)||(t.size??-1)-(e.size??-1)}function Tn(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
157
157
|
`,"utf8")}function Tt(t,e,i){let n=`${e}
|
|
158
|
-
${Ea(i)}`;t.update(`${Buffer.byteLength(n,"utf8")}:`),t.update(n)}function
|
|
159
|
-
`),t.omissionOverflow&&Tt(a,"existing-overflow",t.omissionOverflow);let o=(d,p)=>{p||(n+=1),r+=1,Tt(a,"omission",d)},s=d=>{n+=1,r+=1,Tt(a,"entry",d)},c=()=>{for(let d=i.length-1;d>=0;d-=1){let p=i[d];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(d,1),p}return null},l=()=>({...t,complete:n===0,entries:e,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Tn(u)>Gt;){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(e.length>0){let p=Math.max(1,Math.ceil(e.length/4));for(let m of e.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let f=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${f}`,hash:f,count:r}}}function Oc(t){let e=hn(t),i=e.entries.map((r,a)=>
|
|
160
|
-
`);let i=0;np(t.baseline,t.current,r=>{if(i>=t.detailedChangeCount){Tt(e,"change",r);let a=0;for(let o of t.declaredArtifacts)Aa(o,r.path)&&(a+=1,Tt(e,"change-attribution",o));Tt(e,"change-end",{attributionCount:a}),a===0&&Tt(e,"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",t.baseline],["current",t.current]])for(let o of a.omitted)n>=t.detailedOmissionCount&&Tt(e,"snapshot-omission",{source:r,...o}),n+=1;return e.digest("hex")}function op(t,e,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=Rk(t,e,r,i.gitChangedPaths),s=W(xn,t),c=W(xn,e),l=[];for(let[g,b]of[["baseline",t],["current",e]])for(let y of b.omitted){if(l.length>=pk)break;l.push(at({kind:"snapshot-omission",source:g,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${g} snapshot omitted ${y.path}: ${y.reason}`))}let u=t.omitted.length+e.omitted.length,f=[...Uh("baseline",t),...Uh("current",e),...o.totalChanges===0&&a===null?[at({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")]:[]],d=()=>{if(i.gitChangedPaths===void 0)return;let g=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(b=>g.has(b)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(b=>!g.has(b))}},p=g=>{let b=o.candidates.slice(0,g.detailedChangeCount),y=b.filter(qe=>qe.attributedTo.length===0),R=o.totalChanges-b.length,O=o.totalUnattributed-y.length,B=u-g.detailedOmissionCount,H=O+B,D=[...y.map(qe=>at({kind:"unattributed-change",source:"implementation-scope",path:qe.path,evidence:{after:qe.after,before:qe.before,changeKind:qe.kind}},`Changed path is not covered by a declared artifact: ${qe.path}`)),...l.slice(0,g.detailedOmissionCount),...f,...R>0||H>0?[ap(g.overflowHash,{changes:R,unattributed:O,unresolved:H})]:[]],J=kk(D),Be=g.includeGitAdvisory?d():void 0;return{schema:Ic,contractHash:n,baselineProjectionRef:_c(s),baselineProjectionHash:s,currentProjectionRef:_c(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:r,changes:b,unattributed:y,unresolvedScopes:J,noCodeReason:a,...Be?{gitAdvisory:Be}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:w});if(Tn({...g,scopeHash:w})<=Gt)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 k=o.totalChanges>m||u>h?Pk({baseline:t,current:e,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):w,N=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:k}),S={...N,scopeHash:W(tp,N)};if(Tn(S)>Gt)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function Hc(t){let e=Oc(t.baseline),i=Oc(t.current),n=rp(t);return{authority:n,baseline:e,current:i,scope:op(e,i,n)}}var Ak=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function ot(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function st(t,e,i,n){let r=new Set([...e,...i]),a=Object.keys(t).filter(s=>!r.has(s)),o=e.filter(s=>!(s in t));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 Kt(t,e){if(typeof t!="string"||!$c.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Yh(t,e,i){let n=_c(e);if(t!==n)throw new Error(`${i} ref/hash mismatch`);return n}function Ca(t,e){let i=ot(t,"Native snapshot projection");if(st(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==ep)throw new Error("Native snapshot projection schema is invalid");let n=hn({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=Oc(n);if(W(xn,i)!==W(xn,r))throw new Error("Native snapshot projection is not canonical");let a=W(xn,r);if(e!==void 0&&Kt(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Mc(t,e){let i=ot(t,`Declared artifact ${e}`);if(st(i,["path","kind"],[],`Declared artifact ${e}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${e} kind is invalid`);return{path:It(i.path,`Declared artifact ${e} path`),kind:i.kind}}function Xh(t,e){if(t===null)return null;let i=ot(t,e);return st(i,["hash","size"],[],e),{hash:Kt(i.hash,`${e} hash`),size:wi(i.size,`${e} size`)}}function Qh(t,e){let i=ot(t,`Implementation change ${e}`);if(st(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${e}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${e} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${e} attributedTo must be an array`);let n=i.attributedTo.map(Mc),r=Pa(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=Xh(i.before,`Implementation change ${e} before`),o=Xh(i.after,`Implementation change ${e} 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 ${e} before/after state is invalid`);return{path:It(i.path,`Implementation change ${e} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function xk(t,e){let i=ot(t,`Unresolved scope ${e}`);st(i,["id","kind","source","path","reason"],[],`Unresolved scope ${e}`);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 ${e} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${e} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${e} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${e} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${e} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?ip(i.path,`Unresolved scope ${e} path`):It(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Ra(t,e){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${e} must be an array of paths`);let i=t.map((r,a)=>It(r,`${e} ${a}`)),n=[...new Set(i)].sort(oe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${e} must be sorted and unique`);return i}function xa(t){let e=ot(t,"Native implementation scope"),i=[...Ak].filter(b=>b!=="gitAdvisory");if(st(e,i,["gitAdvisory"],"Native implementation scope"),e.schema!==Ic)throw new Error("Native implementation scope schema is invalid");let n=Kt(e.contractHash,"Implementation scope contractHash"),r=Kt(e.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Yh(e.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Kt(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Yh(e.currentProjectionRef,o,"Implementation scope current projection");if(typeof e.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(e.declaredArtifacts)||!Array.isArray(e.changes)||!Array.isArray(e.unattributed)||!Array.isArray(e.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=e.declaredArtifacts.map(Mc);if(JSON.stringify(c)!==JSON.stringify(Pa(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(Qh),u=[...l].sort((b,y)=>oe(b.path,y.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(b=>b.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(b=>`${b.kind}:${b.path}`));if(l.some(b=>b.attributedTo.some(y=>!f.has(`${y.kind}:${y.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(b=>JSON.stringify(b.attributedTo)!==JSON.stringify(c.filter(y=>Aa(y,b.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=e.unattributed.map(Qh),p=l.filter(b=>b.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=e.unresolvedScopes.map(xk),h=m.filter(b=>b.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:Ck(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 w=e.noCodeReason,E=[...p.map(b=>at({kind:"unattributed-change",source:"implementation-scope",path:b.path,evidence:{after:b.after,before:b.before,changeKind:b.kind}},`Changed path is not covered by a declared artifact: ${b.path}`)),...l.length+(v?.changes??0)===0&&w===null?[at({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")]:[]],k=m.filter(b=>b.kind==="unattributed-change"||b.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(jc))||new Set(m.map(b=>b.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(E.sort(jc))||e.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let N;if(e.gitAdvisory!==void 0){let b=ot(e.gitAdvisory,"Implementation scope Git advisory");if(st(b,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),b.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let y=Ra(b.changedPaths,"Git changed paths"),R=Ra(b.pathsPresentInSnapshotChanges,"Git present paths"),O=Ra(b.pathsAbsentFromSnapshotChanges,"Git absent paths"),B=[...R,...O].sort(oe),H=new Set(l.map(D=>D.path));if(JSON.stringify(B)!==JSON.stringify(y)||(v?.changes??0)===0&&R.some(D=>!H.has(D))||O.some(D=>H.has(D)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:y,pathsPresentInSnapshotChanges:R,pathsAbsentFromSnapshotChanges:O}}let S={schema:Ic,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:w,...N?{gitAdvisory:N}:{}},g=Kt(e.scopeHash,"Implementation scope scopeHash");if(W(tp,S)!==g)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:g}}function Tk(t){let e=ot(t,"Native implementation scope authority");if(st(e,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(e.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=e.declaredArtifacts.map(Mc);if(JSON.stringify(i)!==JSON.stringify(Pa(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;e.gitChangedPaths!==void 0&&(n=Ra(e.gitChangedPaths,"Native implementation scope authority Git paths"));let r=rp({contractHash:e.contractHash,declaredArtifacts:i,noCodeReason:e.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==e.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Ta(t){let e=ot(t,"Native implementation scope bundle");st(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Tk(e.authority),n=Ca(e.baseline),r=Ca(e.current),a=xa(e.scope),o=op(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 sp(t){let e=xa(t.scope);return Ta({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{}},baseline:t.baseline,current:t.current,scope:e})}var up=/^[a-f0-9]{64}$/u;var Ik="comet.native.acceptance-trace.v2",_k="comet.native.partial-allowance.v1",Ok="comet.native.verification-evidence.v2";function ct(t,e){if(!up.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function fp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native evidence source revision must be a positive integer");return t}function dp(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native evidence change name: ${t}`);return t}function Lc(t,e,i=2e3){let n=Ce(t).trim();if(n.length===0||n.length>i)throw new Error(`${e} must be between 1 and ${i} characters`);return n}function In(t,e){let i=cp.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||cp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized relative ref`);return t}function jk(t,e,i){let n=In(t,e);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=We(n),a=n.toLowerCase(),o=i?In(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${e} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Dc(t){let e=In(t,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(e))throw new Error("Verification receipt ref must identify a typed v3 receipt");return e}function yi(t,e){return t<e?-1:t>e?1:0}function Ia(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function _a(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));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 hp(t,e){if(typeof t!="string")throw new Error(`${e} is invalid`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} is invalid`);return t}function lp(t,e,i){if(typeof t!="string")throw new Error(`Native ${e} evidence ref is invalid`);let n=`runtime/evidence/${e}/${i}.json`;if(t!==n)throw new Error(`Native ${e} evidence ref/hash mismatch`);return t}function $k(t){let e=Ia(t,"Native acceptance trace");if(_a(e,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),e.schema!=="comet.native.acceptance-trace.v2"||typeof e.nativeRootRef!="string"||typeof e.criteriaHash!="string"||!up.test(e.criteriaHash)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.evidenced)||!Number.isSafeInteger(e.skipped)||!Array.isArray(e.entries))throw new Error("Native acceptance trace is invalid");let i=In(e.nativeRootRef,"Native root ref"),n=e.entries.map((o,s)=>{let c=Ia(o,`Native acceptance trace entry ${s}`);if(_a(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(f=>typeof f!="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(f=>Dc(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yi))||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:In(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Lc(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>yi(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||e.total!==n.length||e.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||e.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:e.criteriaHash,total:e.total,evidenced:e.evidenced,skipped:e.skipped,entries:n},a=ct(e.traceHash,"Native acceptance trace hash");if(W(Ik,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function pp(t){let e=Ia(t,"Native partial allowance");if(_a(e,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),e.schema!=="comet.native.partial-allowance.v1"||typeof e.change!="string"||typeof e.scopeHash!="string"||!Array.isArray(e.scopeIds)||e.scopeIds.length===0||e.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(e.scopeIds)!==JSON.stringify([...new Set(e.scopeIds)].sort(yi))||typeof e.reason!="string"||typeof e.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:dp(e.change),scopeHash:ct(e.scopeHash,"Native partial allowance scopeHash"),scopeIds:e.scopeIds,reason:Lc(e.reason,"Partial allowance reason"),confirmedSummary:Lc(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:fp(e.sourceRevision),confirmedAt:hp(e.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==e.reason||i.confirmedSummary!==e.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=ct(e.allowanceHash,"Native partial allowance hash");if(W(_k,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Fc(t){let e=Ia(t,"Native verification evidence");if(_a(e,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),e.schema!=="comet.native.verification-evidence.v2"||typeof e.change!="string"||e.result!=="pass"&&e.result!=="fail"||e.freshness!=="complete"&&e.freshness!=="partial"||typeof e.implementationScopeHash!="string"||typeof e.reportRef!="string"||!Array.isArray(e.requiredReceiptRefs)||!Array.isArray(e.receiptRefs))throw new Error("Native verification evidence is invalid");let i=ct(e.implementationScopeHash,"Native verification implementation scope hash"),n=$k(e.acceptanceTrace),r=ct(e.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=e.partialAllowanceRef!==null||e.partialAllowanceHash!==null;if(e.partialAllowanceRef===null!=(e.partialAllowanceHash===null)||e.freshness==="complete"&&a||e.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=e.partialAllowanceHash===null?null:ct(e.partialAllowanceHash,"Native verification allowance hash"),s=e.receiptRefs.map(d=>Dc(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(yi)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(d=>d.evidenceRefs))].sort(yi);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=e.requiredReceiptRefs.map(d=>Dc(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yi)))throw new Error("Native required receipt refs must be canonical");if(e.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:dp(e.change),sourceRevision:fp(e.sourceRevision),result:e.result,freshness:e.freshness,contractHash:ct(e.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:lp(e.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:jk(e.reportRef,"Native verification report ref"),reportHash:ct(e.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:lp(e.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:hp(e.createdAt,"Native verification timestamp")},f=ct(e.envelopeHash,"Native verification envelope hash");if(W(Ok,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}function Bc(t,e){if(typeof t!="string"||t.trim().length===0||t.length>4096)throw new Error(`${e} must be between 1 and 4096 characters`)}var Hk=/^[a-f0-9]{64}$/u;var mp=["disposition","overrideSummaryHash","signatureHash"],Mk=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function Vc(t,e){return t<e?-1:t>e?1:0}function Lk(t,e,i){let n=Object.keys(t).sort(Vc);if(n.length!==e.length||n.some((r,a)=>r!==e[a]))throw new Error(`${i} fields are invalid`)}function Dk(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function qc(t,e){if(typeof t!="string"||!Hk.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Fk(t){if(!Array.isArray(t)||t.length>Tc.maxFailedAcceptanceIds||t.some(e=>typeof e!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(e)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(t)].sort(Vc)}function vp(t){let e=Dk(t,"Native repair trajectory projection"),i=Object.keys(e).sort(Vc),n=i.length===mp.length&&i.every((l,u)=>l===mp[u]);n||Lk(e,Mk,"Native repair trajectory projection");let r=qc(e.signatureHash,"Native repair trajectory signature hash");if(e.disposition!=="continue"&&e.disposition!=="warn"&&e.disposition!=="manual-stop"&&e.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=e.overrideSummaryHash===null?null:qc(e.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&e.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=qc(e.contractHash,"Native repair trajectory contract hash"),s=Fk(e.failedAcceptanceIds),c=Jh(e.failedCheckIds);if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:e.maxVerifyFailures}}var Ni={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:[]},zc=G("comet-native-runtime:v3:semantic-repair-budget"),Bk=[{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function gp(t){return t.skillVersion===Ni.definition.metadata.version&&t.skillHash===zc||Bk.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}async function Oa(t){let i={sequence:(await pi(t.changeDir,t.run.trajectoryRef)).length+1,timestamp:(t.now??new Date).toISOString(),type:t.type,runId:t.run.runId,data:t.data};return await Ah(t.changeDir,t.run.trajectoryRef,i),i}async function Wc(t){let e={runId:t.run.runId,stateVersion:t.run.iteration,trajectoryOffset:t.trajectoryOffset,contextHash:null,artifactsHash:G(t.evidenceHash),createdAt:(t.now??new Date).toISOString()};return await xh(t.changeDir,t.run.checkpointRef,e),e}function wp(t){return G(JSON.stringify({summary:t.summary,confirmed:t.confirmed??!1,artifacts:[...t.artifacts??[]].sort(),noCodeReason:t.noCodeReason??null,verificationResult:t.verificationResult??null,verificationReport:t.verificationReport??null,allowPartialScopeHash:t.allowPartialScopeHash??null,partialReason:t.partialReason??null,repairOverrideSignature:t.repairOverrideSignature??null,repairOverrideSummary:t.repairOverrideSummary??null}))}var Cp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],zk=new Set(Cp),Pp=new Set([...Cp,"minimum_runtime_version","revision"]),Wk=new Set([...Pp,"operation"]),Jk=512*1024,Kc=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Kk=new Set([...Kc,"implementationScopeHash","repairScopeHash","repairStagnation"]),Gc=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 Xc(t,e){return Vk.join(Y(t,e),"runtime","transition.json")}function Gk(t){return`transition-${t}`}async function Uk(t,e,i){let n=Gk(e);return un(t,n,i)}async function $a(t,e,i,n){let r=await Uk(t,e,i);try{return await n()}finally{await fn(r)}}function Ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function Qc(t,e){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function ja(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ge(t,e){return Yc(t,e)}function Uc(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal event data is invalid");let i=t,n=Object.keys(i),r=n.find(u=>!Kk.has(u)),a=[...Kc].find(u=>!Object.hasOwn(i,u)),o=Kc.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!==e)throw new Error("Native transition journal event evidence hash mismatch");if(Bc(i.summary,"Native transition journal event summary"),Ce(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&&(Bc(i.noCodeReason,"Native transition journal event no-code reason"),Ce(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")?vp(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:e,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function Yk(t,e){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,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 Uc({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return Uc(t,e)}function Zc(t,e,i=!1){if(t.change!==e)throw new Error("Native transition journal change mismatch");if(typeof t.id!="string"||t.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof t.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(t.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?Yk(t.eventData,t.evidenceHash):Uc(t.eventData,t.evidenceHash),r=mc(t.nextRun),a=t.previousRun===null?null:mc(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:r,eventData:n}}function yp(t,e,i=!1){if(t.skill!==Ni.definition.metadata.name||(i?!gp(t):t.skillVersion!==Ni.definition.metadata.version||t.skillHash!==zc)||t.orchestration!==Ni.definition.orchestration.mode||t.pendingRef!==Ke.pendingRef||t.trajectoryRef!==Ke.trajectoryRef||t.contextRef!==Ke.contextRef||t.artifactsRef!==Ke.artifactsRef||t.checkpointRef!==Ke.checkpointRef)throw new Error(`Native transition journal ${e} metadata or storage refs are invalid`)}function Np(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,retries:t.retries}}function bp(t,e){if(t.status!=="running")throw new Error(`Native transition journal ${e} status must be running`);if(t.pending!==null)throw new Error(`Native transition journal ${e} pending action must be null`)}function el(t,e,i,n=!1){let{previousRun:r,nextRun:a}=i;if(yp(a,"next Run",n||r!==null),bp(a,"next Run"),a.runId!==e.run_id||a.currentStep!==e.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(t.run_id!==null||t.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(yp(r,"previous Run",!0),bp(r,"previous Run"),t.run_id!==r.runId||r.currentStep!==t.phase||e.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(!Yc(Np(r),Np(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Xk(t,e,i){return G(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function Ap(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Sp(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function tl(t,e,i,n,r=!1){let a=i.eventData,o=Sp(t),s=Sp(e);if(a.previousPhase!==t.phase||a.nextPhase!==e.phase)throw new Error("Native transition journal event phases do not match its states");if(t.archived||e.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=t.name===e.name&&t.language===e.language&&t.brief===e.brief&&t.approval===e.approval&&("approved_contract_hash"in t?"approved_contract_hash"in e&&t.approved_contract_hash===e.approved_contract_hash:!("approved_contract_hash"in e))&&t.created_at===e.created_at&&t.run_id===e.run_id&&Yc(t.spec_changes,e.spec_changes),l=wp({summary:a.summary});if(!(t.phase==="archive"&&t.verification_result==="pass"||t.phase==="verify"&&t.verification_result==="pending")||e.phase!=="build"||e.verification_result!=="pending"||e.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=Xk(t.name,a.summary,e.spec_changes),l=G(`spec-rebase:${t.name}:${a.summary}`);if(t.phase==="shape"||e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||e.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in e&&(e.implementation_scope!==null||e.verification_evidence!==null||e.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(t.phase==="shape"){if(e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||e.verification_result!=="pending"||t.verification_report!==null||e.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(t.phase==="build"){if(e.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||e.verification_result!=="pending"||e.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(t.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||e.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!==a.verificationResult||e.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 Qk(t,e){let i=Ha(t);if(Qc(i,Wk),i.schema!==mi)throw new Error(`Expected Native transition schema ${mi}`);let n=ja(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 ${mi} minimum_runtime_version must be ${3}`);let r=ja(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=Zc(i,e),o=rt(i.previousState),s=rt(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native transition journal state mismatch");if(tl(o,s,a,i.operation),el(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:mi,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function Zk(t,e){let i=Ha(t);if(Qc(i,zk),i.schema!==Nn)throw new Error(`Expected Native transition schema ${Nn}`);let n=Zc(i,e,!0),r=Rn(i.previousState),a=Rn(i.nextState);if(r.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return tl(r,a,n,Ap(r,a,n.eventData),!0),el(r,a,n,!0),{schema:Nn,id:n.id,change:e,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function eE(t,e){let i=Ha(t);if(Qc(i,Pp),i.schema!==vi)throw new Error(`Expected Native transition schema ${vi}`);if(ja(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${vi} minimum_runtime_version must be 2`);let r=ja(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Zc(i,e,!0),o=Cn(i.previousState),s=Cn(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(tl(o,s,a,Ap(o,s,a.eventData),!0),el(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:vi,minimum_runtime_version:2,revision:r,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function tE(t,e){let i=Ha(t);if(i.schema===mi)return{status:"current",journal:Qk(i,e)};if(i.schema===Nn)return{status:"migration-required",journal:Zk(i,e)};if(i.schema===vi)return{status:"migration-required",journal:eE(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function iE(t,e){let i=Xc(t,e);await q(t.nativeRoot,i);try{let n=await tt({root:t.nativeRoot,file:i,maxBytes:Jk,label:`Native transition journal ${e}`});return tE(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Jc(t,e){let i=await iE(t,e);if(!i)return null;if(i.status==="migration-required")throw new Gc(e);return i.journal}function kp(t,e){if(Ge(t,e.nextRun))return"next";if(e.previousRun===null){if(t===null)return"previous"}else if(Ge(t,e.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${e.change}; recovery journal was preserved`)}function Ep(t,e){if(Ge(t,e.nextState))return"next";if(Ge(t,e.previousState))return"previous";throw new Error(`Native transition change content changed for ${e.change}; recovery journal was preserved`)}function nE(t){let{journal:e}=t;return xp({sequence:t.sequence,timestamp:e.createdAt,type:t.type,runId:e.nextRun.runId,data:t.type==="run_started"?{runtime:"comet-native",phase:e.previousState.phase,transitionId:e.id}:{...e.eventData,transitionId:e.id}})}function xp(t){return{sequence:t.sequence,timestamp:t.timestamp,type:t.type,runId:t.runId,data:t.data}}function Rp(t,e){let i=t.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===e.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>(e.previousRun===null?1:0)||r.length>1||e.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${e.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=nE({sequence:a.index+1,journal:e,type:a.event.type});if(!Ge(xp(a.event),o))throw new Error(`Native trajectory event changed for transition ${e.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function il(t,e,i){if(await Pn(t,e))throw new Error(`Native schema migration is incomplete for ${e}; run doctor --repair`);await va(t,e);let n=await Jc(t,e);if(!n)return null;let r=Y(t,e),a=Rp(await pi(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([yn(r),Ne(t,e)]),c=kp(o,n),l=Ep(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 vc(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ge(await yn(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 ya(t,n.nextState,n.previousState.revision);if(!Ge(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ge(await Ne(t,e),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await Jc(t,e);if(!u||!Ge(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let f=Rp(await pi(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(f.started||await Oa({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 d=f.transitioned;d||(d=await Oa({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Wc({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([yn(r),Ne(t,e)]);kp(p,{...n,previousRun:n.nextRun}),Ep(m,{...n,previousState:n.nextState});let h=await Jc(t,e);if(!h||!Ge(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await qk.rm(Xc(t,e),{force:!0}),n.nextState}async function Tp(t,e,i){let n=await Vh(t,e);if(!n)return null;if(await zh(t,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ya(t,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Wh(t,n.checkpoint),await i?.afterProgressWritten?.(n),await rE.rm(Cc(t,e),{force:!0}),n}async function nl(t,e){await il(t,e),await Tp(t,e)}var Ma="scoped-text-safety",aE=1,oE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var sE="comet.native.checker-policy.v1";var t_=W(sE,{policy:Ma,version:aE,limits:oE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var cE=["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"],i_=new Set(cE);var u_=512*1024;import Dp from"node:path";import Ip from"node:path";var lE="comet.native.acceptance.v1",uE=/^acceptance-[a-f0-9]{64}$/u,fE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),dE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var p_=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),On=Object.freeze({maxCriteria:1024}),_n="<!-- comet-native:acceptance-evidence:start -->",bi="<!-- comet-native:acceptance-evidence:end -->";function ol(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function rl(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let n=i[1][0];return e===null?{marker:n,length:i[1].length}:n===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function _p(t){return t.includes("-->")||t.includes("--!>")}function*Si(t){let e=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
158
|
+
${Ea(i)}`;t.update(`${Buffer.byteLength(n,"utf8")}:`),t.update(n)}function bk(t){if(Tn(t)<=Gt)return t;let e=[...t.entries],i=[...t.omitted],n=t.omittedCount,r=t.omissionOverflow?.count??0,a=Zh("sha256");a.update(`${hk}
|
|
159
|
+
`),t.omissionOverflow&&Tt(a,"existing-overflow",t.omissionOverflow);let o=(d,p)=>{p||(n+=1),r+=1,Tt(a,"omission",d)},s=d=>{n+=1,r+=1,Tt(a,"entry",d)},c=()=>{for(let d=i.length-1;d>=0;d-=1){let p=i[d];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return i.splice(d,1),p}return null},l=()=>({...t,complete:n===0,entries:e,omitted:i,omittedCount:n,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:r}}),u=l();for(;Tn(u)>Gt;){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(e.length>0){let p=Math.max(1,Math.ceil(e.length/4));for(let m of e.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let f=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${f}`,hash:f,count:r}}}function Oc(t){let e=hn(t),i=e.entries.map((r,a)=>gk(r,`Snapshot entry ${a}`));if(i.sort(yk),new Set(i.map(r=>r.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let n=e.omitted.map((r,a)=>wk(r,`Snapshot omission ${a}`));return n.sort(Nk),bk({schema:ep,origin:e.origin,...e.capture?{capture:e.capture}:{},complete:e.complete,limits:{maxFiles:e.limits.maxFiles,maxFileBytes:e.limits.maxFileBytes,maxTotalBytes:e.limits.maxTotalBytes,maxManifestBytes:e.limits.maxManifestBytes,...e.limits.maxDurationMs===void 0?{}:{maxDurationMs:e.limits.maxDurationMs}},...e.policy?{policy:e.policy}:{},entries:i,omitted:n,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:{ref:e.omissionOverflow.ref,hash:e.omissionOverflow.hash,count:e.omissionOverflow.count}}:{}})}function Pa(t){let e=new Map;for(let[i,n]of t.entries()){if(n.kind!=="file"&&n.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let r={path:It(n.path,`Declared artifact ${i} path`),kind:n.kind},a=e.get(r.path);if(a&&a.kind!==r.kind)throw new Error(`Declared artifact path has conflicting kinds: ${r.path}`);e.set(r.path,r)}return[...e.values()].sort((i,n)=>oe(i.path,n.path)||oe(i.kind,n.kind))}function Aa(t,e){return t.kind==="file"?t.path===e:e===t.path||e.startsWith(`${t.path}/`)}function Gh(t){return t?{hash:t.hash,size:t.size}:null}function np(t,e,i){let n=0,r=0;for(;n<t.entries.length||r<e.entries.length;){let a=t.entries[n],o=e.entries[r],s=a===void 0?1:o===void 0?-1:oe(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&&!e.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Gh(c),after:Gh(l)})}}function Sk(t,e){return{...t,attributedTo:e.filter(i=>Aa(i,t.path))}}function at(t,e){return{id:`scope:${W(fk,t)}`,kind:t.kind,source:t.source,path:t.path,reason:e}}function kk(t,e){let i=e.omitted.map(n=>at({kind:"snapshot-omission",source:t,path:n.path,evidence:{reason:n.reason,size:n.size,type:n.type}},`${t} snapshot omitted ${n.path}: ${n.reason}`));return e.complete||i.push(at({kind:"snapshot-incomplete",source:t,path:null,evidence:{omittedCount:e.omittedCount}},`${t} snapshot is incomplete`)),e.omissionOverflow&&i.push(at({kind:"snapshot-omission-overflow",source:t,path:null,evidence:{count:e.omissionOverflow.count,hash:e.omissionOverflow.hash,ref:e.omissionOverflow.ref}},`${t} snapshot has ${e.omissionOverflow.count} unlisted omissions`)),i}function Uh(t,e){return kk(t,{...e,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function jc(t,e){return oe(t.kind,e.kind)||oe(t.source,e.source)||vk(t.path,e.path)||oe(t.id,e.id)}function Ek(t){return[...new Map(t.map(i=>[i.id,i])).values()].sort(jc)}function Rk(t){return[...new Set(t.map((e,i)=>It(e,`Git path ${i}`)))].sort(oe)}function rp(t){if(typeof t.contractHash!="string"||!$c.test(t.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:t.contractHash,declaredArtifacts:Pa(t.declaredArtifacts),noCodeReason:t.noCodeReason?.trim()||null,...t.gitChangedPaths===void 0?{}:{gitChangedPaths:Rk(t.gitChangedPaths)}}}function Ck(t,e,i,n){let r=[],a=n===void 0?null:new Set(n),o=[],s=0,c=!1,l=0,u=0;return np(t,e,f=>{let d=i.some(p=>Aa(p,f.path));if(l+=1,d||(u+=1),a?.has(f.path)&&o.push(f.path),!c&&r.length<pk){let p=Sk(f,i),m=Tn(p);s+m<=Gt?(r.push(p),s+=m):c=!0}}),{candidates:r,gitPathsPresentInChanges:o,totalChanges:l,totalUnattributed:u}}function ap(t,e){return at({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:e.changes,hash:t,unattributedCount:e.unattributed,unresolvedCount:e.unresolved}},`Implementation scope summarized ${e.changes} additional change details and ${e.unresolved} unresolved details (${e.unattributed} unattributed); overflow hash ${t}`)}function Pk(t){let e=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(t.reason);if(!e)throw new Error("Implementation scope detail overflow is invalid");let i={changes:wi(Number(e[1]),"Scope overflow change count"),unresolved:wi(Number(e[2]),"Scope overflow unresolved count"),unattributed:wi(Number(e[3]),"Scope overflow unattributed count")},n=Kt(e[4],"Scope detail overflow hash");if(JSON.stringify(t)!==JSON.stringify(ap(n,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:n}}function Ak(t){let e=Zh("sha256");e.update(`${dk}
|
|
160
|
+
`);let i=0;np(t.baseline,t.current,r=>{if(i>=t.detailedChangeCount){Tt(e,"change",r);let a=0;for(let o of t.declaredArtifacts)Aa(o,r.path)&&(a+=1,Tt(e,"change-attribution",o));Tt(e,"change-end",{attributionCount:a}),a===0&&Tt(e,"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",t.baseline],["current",t.current]])for(let o of a.omitted)n>=t.detailedOmissionCount&&Tt(e,"snapshot-omission",{source:r,...o}),n+=1;return e.digest("hex")}function op(t,e,i){let{contractHash:n,declaredArtifacts:r,noCodeReason:a}=i,o=Ck(t,e,r,i.gitChangedPaths),s=W(xn,t),c=W(xn,e),l=[];for(let[g,b]of[["baseline",t],["current",e]])for(let y of b.omitted){if(l.length>=mk)break;l.push(at({kind:"snapshot-omission",source:g,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${g} snapshot omitted ${y.path}: ${y.reason}`))}let u=t.omitted.length+e.omitted.length,f=[...Uh("baseline",t),...Uh("current",e),...o.totalChanges===0&&a===null?[at({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")]:[]],d=()=>{if(i.gitChangedPaths===void 0)return;let g=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(b=>g.has(b)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(b=>!g.has(b))}},p=g=>{let b=o.candidates.slice(0,g.detailedChangeCount),y=b.filter(qe=>qe.attributedTo.length===0),R=o.totalChanges-b.length,O=o.totalUnattributed-y.length,B=u-g.detailedOmissionCount,H=O+B,D=[...y.map(qe=>at({kind:"unattributed-change",source:"implementation-scope",path:qe.path,evidence:{after:qe.after,before:qe.before,changeKind:qe.kind}},`Changed path is not covered by a declared artifact: ${qe.path}`)),...l.slice(0,g.detailedOmissionCount),...f,...R>0||H>0?[ap(g.overflowHash,{changes:R,unattributed:O,unresolved:H})]:[]],J=Ek(D),Be=g.includeGitAdvisory?d():void 0;return{schema:Ic,contractHash:n,baselineProjectionRef:_c(s),baselineProjectionHash:s,currentProjectionRef:_c(c),currentProjectionHash:c,complete:J.length===0,declaredArtifacts:r,changes:b,unattributed:y,unresolvedScopes:J,noCodeReason:a,...Be?{gitAdvisory:Be}:{}}},m=o.candidates.length,h=l.length,v=i.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let g=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:w});if(Tn({...g,scopeHash:w})<=Gt)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 k=o.totalChanges>m||u>h?Ak({baseline:t,current:e,declaredArtifacts:r,detailedChangeCount:m,detailedOmissionCount:h}):w,N=p({detailedChangeCount:m,detailedOmissionCount:h,includeGitAdvisory:v,overflowHash:k}),S={...N,scopeHash:W(tp,N)};if(Tn(S)>Gt)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function Hc(t){let e=Oc(t.baseline),i=Oc(t.current),n=rp(t);return{authority:n,baseline:e,current:i,scope:op(e,i,n)}}var xk=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","scopeHash"]);function ot(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function st(t,e,i,n){let r=new Set([...e,...i]),a=Object.keys(t).filter(s=>!r.has(s)),o=e.filter(s=>!(s in t));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 Kt(t,e){if(typeof t!="string"||!$c.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Yh(t,e,i){let n=_c(e);if(t!==n)throw new Error(`${i} ref/hash mismatch`);return n}function Ca(t,e){let i=ot(t,"Native snapshot projection");if(st(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==ep)throw new Error("Native snapshot projection schema is invalid");let n=hn({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=Oc(n);if(W(xn,i)!==W(xn,r))throw new Error("Native snapshot projection is not canonical");let a=W(xn,r);if(e!==void 0&&Kt(e,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return r}function Mc(t,e){let i=ot(t,`Declared artifact ${e}`);if(st(i,["path","kind"],[],`Declared artifact ${e}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${e} kind is invalid`);return{path:It(i.path,`Declared artifact ${e} path`),kind:i.kind}}function Xh(t,e){if(t===null)return null;let i=ot(t,e);return st(i,["hash","size"],[],e),{hash:Kt(i.hash,`${e} hash`),size:wi(i.size,`${e} size`)}}function Qh(t,e){let i=ot(t,`Implementation change ${e}`);if(st(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${e}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${e} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${e} attributedTo must be an array`);let n=i.attributedTo.map(Mc),r=Pa(n);if(JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Implementation change ${e} attribution must be sorted and unique`);let a=Xh(i.before,`Implementation change ${e} before`),o=Xh(i.after,`Implementation change ${e} 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 ${e} before/after state is invalid`);return{path:It(i.path,`Implementation change ${e} path`),kind:i.kind,before:a,after:o,attributedTo:n}}function Tk(t,e){let i=ot(t,`Unresolved scope ${e}`);st(i,["id","kind","source","path","reason"],[],`Unresolved scope ${e}`);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 ${e} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${e} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${e} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${e} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${e} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?ip(i.path,`Unresolved scope ${e} path`):It(i.path,`Unresolved scope ${e} path`),reason:i.reason}}function Ra(t,e){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`${e} must be an array of paths`);let i=t.map((r,a)=>It(r,`${e} ${a}`)),n=[...new Set(i)].sort(oe);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`${e} must be sorted and unique`);return i}function xa(t){let e=ot(t,"Native implementation scope"),i=[...xk].filter(b=>b!=="gitAdvisory");if(st(e,i,["gitAdvisory"],"Native implementation scope"),e.schema!==Ic)throw new Error("Native implementation scope schema is invalid");let n=Kt(e.contractHash,"Implementation scope contractHash"),r=Kt(e.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Yh(e.baselineProjectionRef,r,"Implementation scope baseline projection"),o=Kt(e.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Yh(e.currentProjectionRef,o,"Implementation scope current projection");if(typeof e.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(e.declaredArtifacts)||!Array.isArray(e.changes)||!Array.isArray(e.unattributed)||!Array.isArray(e.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=e.declaredArtifacts.map(Mc);if(JSON.stringify(c)!==JSON.stringify(Pa(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=e.changes.map(Qh),u=[...l].sort((b,y)=>oe(b.path,y.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(b=>b.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(b=>`${b.kind}:${b.path}`));if(l.some(b=>b.attributedTo.some(y=>!f.has(`${y.kind}:${y.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(b=>JSON.stringify(b.attributedTo)!==JSON.stringify(c.filter(y=>Aa(y,b.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=e.unattributed.map(Qh),p=l.filter(b=>b.attributedTo.length===0);if(JSON.stringify(d)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let m=e.unresolvedScopes.map(Tk),h=m.filter(b=>b.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:Pk(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 w=e.noCodeReason,E=[...p.map(b=>at({kind:"unattributed-change",source:"implementation-scope",path:b.path,evidence:{after:b.after,before:b.before,changeKind:b.kind}},`Changed path is not covered by a declared artifact: ${b.path}`)),...l.length+(v?.changes??0)===0&&w===null?[at({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")]:[]],k=m.filter(b=>b.kind==="unattributed-change"||b.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(jc))||new Set(m.map(b=>b.id)).size!==m.length||JSON.stringify(k)!==JSON.stringify(E.sort(jc))||e.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let N;if(e.gitAdvisory!==void 0){let b=ot(e.gitAdvisory,"Implementation scope Git advisory");if(st(b,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),b.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let y=Ra(b.changedPaths,"Git changed paths"),R=Ra(b.pathsPresentInSnapshotChanges,"Git present paths"),O=Ra(b.pathsAbsentFromSnapshotChanges,"Git absent paths"),B=[...R,...O].sort(oe),H=new Set(l.map(D=>D.path));if(JSON.stringify(B)!==JSON.stringify(y)||(v?.changes??0)===0&&R.some(D=>!H.has(D))||O.some(D=>H.has(D)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:y,pathsPresentInSnapshotChanges:R,pathsAbsentFromSnapshotChanges:O}}let S={schema:Ic,contractHash:n,baselineProjectionRef:a,baselineProjectionHash:r,currentProjectionRef:s,currentProjectionHash:o,complete:e.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:m,noCodeReason:w,...N?{gitAdvisory:N}:{}},g=Kt(e.scopeHash,"Implementation scope scopeHash");if(W(tp,S)!==g)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:g}}function Ik(t){let e=ot(t,"Native implementation scope authority");if(st(e,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths"],"Native implementation scope authority"),!Array.isArray(e.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=e.declaredArtifacts.map(Mc);if(JSON.stringify(i)!==JSON.stringify(Pa(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(e.noCodeReason!==null&&(typeof e.noCodeReason!="string"||e.noCodeReason.length===0||e.noCodeReason.trim()!==e.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let n;e.gitChangedPaths!==void 0&&(n=Ra(e.gitChangedPaths,"Native implementation scope authority Git paths"));let r=rp({contractHash:e.contractHash,declaredArtifacts:i,noCodeReason:e.noCodeReason,...n===void 0?{}:{gitChangedPaths:n}});if(r.contractHash!==e.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return r}function Ta(t){let e=ot(t,"Native implementation scope bundle");st(e,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=Ik(e.authority),n=Ca(e.baseline),r=Ca(e.current),a=xa(e.scope),o=op(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 sp(t){let e=xa(t.scope);return Ta({authority:{contractHash:e.contractHash,declaredArtifacts:e.declaredArtifacts,noCodeReason:e.noCodeReason,...e.gitAdvisory?{gitChangedPaths:e.gitAdvisory.changedPaths}:{}},baseline:t.baseline,current:t.current,scope:e})}var up=/^[a-f0-9]{64}$/u;var _k="comet.native.acceptance-trace.v2",Ok="comet.native.partial-allowance.v1",jk="comet.native.verification-evidence.v2";function ct(t,e){if(!up.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function fp(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native evidence source revision must be a positive integer");return t}function dp(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error(`Invalid Native evidence change name: ${t}`);return t}function Lc(t,e,i=2e3){let n=Ce(t).trim();if(n.length===0||n.length>i)throw new Error(`${e} must be between 1 and ${i} characters`);return n}function In(t,e){let i=cp.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||cp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized relative ref`);return t}function $k(t,e,i){let n=In(t,e);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(n))return n;let r=We(n),a=n.toLowerCase(),o=i?In(i,"Native root ref").toLowerCase():null;if(r||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${e} is excluded as sensitive (${r??"native-runtime"}): ${n}`);return n}function Dc(t){let e=In(t,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(e))throw new Error("Verification receipt ref must identify a typed v3 receipt");return e}function yi(t,e){return t<e?-1:t>e?1:0}function Ia(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function _a(t,e,i){let n=new Set(e),r=Object.keys(t).filter(o=>!n.has(o)),a=e.filter(o=>!(o in t));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 hp(t,e){if(typeof t!="string")throw new Error(`${e} is invalid`);let i=new Date(t);if(Number.isNaN(i.valueOf())||i.toISOString()!==t)throw new Error(`${e} is invalid`);return t}function lp(t,e,i){if(typeof t!="string")throw new Error(`Native ${e} evidence ref is invalid`);let n=`runtime/evidence/${e}/${i}.json`;if(t!==n)throw new Error(`Native ${e} evidence ref/hash mismatch`);return t}function Hk(t){let e=Ia(t,"Native acceptance trace");if(_a(e,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),e.schema!=="comet.native.acceptance-trace.v2"||typeof e.nativeRootRef!="string"||typeof e.criteriaHash!="string"||!up.test(e.criteriaHash)||!Number.isSafeInteger(e.total)||!Number.isSafeInteger(e.evidenced)||!Number.isSafeInteger(e.skipped)||!Array.isArray(e.entries))throw new Error("Native acceptance trace is invalid");let i=In(e.nativeRootRef,"Native root ref"),n=e.entries.map((o,s)=>{let c=Ia(o,`Native acceptance trace entry ${s}`);if(_a(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(f=>typeof f!="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(f=>Dc(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yi))||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:In(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Lc(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(n)!==JSON.stringify([...n].sort((o,s)=>yi(o.acceptanceId,s.acceptanceId)))||new Set(n.map(o=>o.acceptanceId)).size!==n.length||e.total!==n.length||e.evidenced!==n.filter(o=>o.evidenceRefs.length>0).length||e.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:e.criteriaHash,total:e.total,evidenced:e.evidenced,skipped:e.skipped,entries:n},a=ct(e.traceHash,"Native acceptance trace hash");if(W(_k,r)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...r,traceHash:a}}function pp(t){let e=Ia(t,"Native partial allowance");if(_a(e,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),e.schema!=="comet.native.partial-allowance.v1"||typeof e.change!="string"||typeof e.scopeHash!="string"||!Array.isArray(e.scopeIds)||e.scopeIds.length===0||e.scopeIds.some(r=>typeof r!="string"||!/^scope:[a-f0-9]{64}$/u.test(r))||JSON.stringify(e.scopeIds)!==JSON.stringify([...new Set(e.scopeIds)].sort(yi))||typeof e.reason!="string"||typeof e.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:dp(e.change),scopeHash:ct(e.scopeHash,"Native partial allowance scopeHash"),scopeIds:e.scopeIds,reason:Lc(e.reason,"Partial allowance reason"),confirmedSummary:Lc(e.confirmedSummary,"Partial allowance confirmation"),sourceRevision:fp(e.sourceRevision),confirmedAt:hp(e.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==e.reason||i.confirmedSummary!==e.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let n=ct(e.allowanceHash,"Native partial allowance hash");if(W(Ok,i)!==n)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:n}}function Fc(t){let e=Ia(t,"Native verification evidence");if(_a(e,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),e.schema!=="comet.native.verification-evidence.v2"||typeof e.change!="string"||e.result!=="pass"&&e.result!=="fail"||e.freshness!=="complete"&&e.freshness!=="partial"||typeof e.implementationScopeHash!="string"||typeof e.reportRef!="string"||!Array.isArray(e.requiredReceiptRefs)||!Array.isArray(e.receiptRefs))throw new Error("Native verification evidence is invalid");let i=ct(e.implementationScopeHash,"Native verification implementation scope hash"),n=Hk(e.acceptanceTrace),r=ct(e.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=e.partialAllowanceRef!==null||e.partialAllowanceHash!==null;if(e.partialAllowanceRef===null!=(e.partialAllowanceHash===null)||e.freshness==="complete"&&a||e.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=e.partialAllowanceHash===null?null:ct(e.partialAllowanceHash,"Native verification allowance hash"),s=e.receiptRefs.map(d=>Dc(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(yi)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(n.entries.flatMap(d=>d.evidenceRefs))].sort(yi);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=e.requiredReceiptRefs.map(d=>Dc(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(yi)))throw new Error("Native required receipt refs must be canonical");if(e.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:dp(e.change),sourceRevision:fp(e.sourceRevision),result:e.result,freshness:e.freshness,contractHash:ct(e.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:r,implementationScopeRef:lp(e.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:$k(e.reportRef,"Native verification report ref"),reportHash:ct(e.reportHash,"Native verification report hash"),acceptanceTrace:n,partialAllowanceRef:o===null?null:lp(e.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:hp(e.createdAt,"Native verification timestamp")},f=ct(e.envelopeHash,"Native verification envelope hash");if(W(jk,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}function Bc(t,e){if(typeof t!="string"||t.trim().length===0||t.length>4096)throw new Error(`${e} must be between 1 and 4096 characters`)}var Mk=/^[a-f0-9]{64}$/u;var mp=["disposition","overrideSummaryHash","signatureHash"],Lk=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"];function Vc(t,e){return t<e?-1:t>e?1:0}function Dk(t,e,i){let n=Object.keys(t).sort(Vc);if(n.length!==e.length||n.some((r,a)=>r!==e[a]))throw new Error(`${i} fields are invalid`)}function Fk(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function qc(t,e){if(typeof t!="string"||!Mk.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function Bk(t){if(!Array.isArray(t)||t.length>Tc.maxFailedAcceptanceIds||t.some(e=>typeof e!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(e)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(t)].sort(Vc)}function vp(t){let e=Fk(t,"Native repair trajectory projection"),i=Object.keys(e).sort(Vc),n=i.length===mp.length&&i.every((l,u)=>l===mp[u]);n||Dk(e,Lk,"Native repair trajectory projection");let r=qc(e.signatureHash,"Native repair trajectory signature hash");if(e.disposition!=="continue"&&e.disposition!=="warn"&&e.disposition!=="manual-stop"&&e.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=e.overrideSummaryHash===null?null:qc(e.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&e.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(n)return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=qc(e.contractHash,"Native repair trajectory contract hash"),s=Bk(e.failedAcceptanceIds),c=Jh(e.failedCheckIds);if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:r,disposition:e.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:e.maxVerifyFailures}}var Ni={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:[]},zc=G("comet-native-runtime:v3:semantic-repair-budget"),qk=[{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function gp(t){return t.skillVersion===Ni.definition.metadata.version&&t.skillHash===zc||qk.some(e=>e.skillVersion===t.skillVersion&&e.skillHash===t.skillHash)}async function Oa(t){let i={sequence:(await pi(t.changeDir,t.run.trajectoryRef)).length+1,timestamp:(t.now??new Date).toISOString(),type:t.type,runId:t.run.runId,data:t.data};return await Ah(t.changeDir,t.run.trajectoryRef,i),i}async function Wc(t){let e={runId:t.run.runId,stateVersion:t.run.iteration,trajectoryOffset:t.trajectoryOffset,contextHash:null,artifactsHash:G(t.evidenceHash),createdAt:(t.now??new Date).toISOString()};return await xh(t.changeDir,t.run.checkpointRef,e),e}function wp(t){return G(JSON.stringify({summary:t.summary,confirmed:t.confirmed??!1,artifacts:[...t.artifacts??[]].sort(),noCodeReason:t.noCodeReason??null,verificationResult:t.verificationResult??null,verificationReport:t.verificationReport??null,allowPartialScopeHash:t.allowPartialScopeHash??null,partialReason:t.partialReason??null,repairOverrideSignature:t.repairOverrideSignature??null,repairOverrideSummary:t.repairOverrideSummary??null}))}var Cp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],Wk=new Set(Cp),Pp=new Set([...Cp,"minimum_runtime_version","revision"]),Jk=new Set([...Pp,"operation"]),Kk=512*1024,Kc=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),Gk=new Set([...Kc,"implementationScopeHash","repairScopeHash","repairStagnation"]),Gc=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 Xc(t,e){return zk.join(Y(t,e),"runtime","transition.json")}function Uk(t){return`transition-${t}`}async function Yk(t,e,i){let n=Uk(e);return un(t,n,i)}async function $a(t,e,i,n){let r=await Yk(t,e,i);try{return await n()}finally{await fn(r)}}function Ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal must be an object");return t}function Qc(t,e){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function ja(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ge(t,e){return Yc(t,e)}function Uc(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native transition journal event data is invalid");let i=t,n=Object.keys(i),r=n.find(u=>!Gk.has(u)),a=[...Kc].find(u=>!Object.hasOwn(i,u)),o=Kc.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!==e)throw new Error("Native transition journal event evidence hash mismatch");if(Bc(i.summary,"Native transition journal event summary"),Ce(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&&(Bc(i.noCodeReason,"Native transition journal event no-code reason"),Ce(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")?vp(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:e,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function Xk(t,e){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t,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 Uc({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},e)}return Uc(t,e)}function Zc(t,e,i=!1){if(t.change!==e)throw new Error("Native transition journal change mismatch");if(typeof t.id!="string"||t.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof t.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(t.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native transition journal timestamp is invalid");let n=i?Xk(t.eventData,t.evidenceHash):Uc(t.eventData,t.evidenceHash),r=mc(t.nextRun),a=t.previousRun===null?null:mc(t.previousRun);return{id:t.id,evidenceHash:t.evidenceHash,createdAt:t.createdAt,previousRun:a,nextRun:r,eventData:n}}function yp(t,e,i=!1){if(t.skill!==Ni.definition.metadata.name||(i?!gp(t):t.skillVersion!==Ni.definition.metadata.version||t.skillHash!==zc)||t.orchestration!==Ni.definition.orchestration.mode||t.pendingRef!==Ke.pendingRef||t.trajectoryRef!==Ke.trajectoryRef||t.contextRef!==Ke.contextRef||t.artifactsRef!==Ke.artifactsRef||t.checkpointRef!==Ke.checkpointRef)throw new Error(`Native transition journal ${e} metadata or storage refs are invalid`)}function Np(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,retries:t.retries}}function bp(t,e){if(t.status!=="running")throw new Error(`Native transition journal ${e} status must be running`);if(t.pending!==null)throw new Error(`Native transition journal ${e} pending action must be null`)}function el(t,e,i,n=!1){let{previousRun:r,nextRun:a}=i;if(yp(a,"next Run",n||r!==null),bp(a,"next Run"),a.runId!==e.run_id||a.currentStep!==e.phase)throw new Error("Native transition journal next Run does not match the next change state");if(r===null){if(t.run_id!==null||t.phase!=="shape"||a.iteration!==1||Object.keys(a.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(yp(r,"previous Run",!0),bp(r,"previous Run"),t.run_id!==r.runId||r.currentStep!==t.phase||e.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(!Yc(Np(r),Np(a)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Qk(t,e,i){return G(JSON.stringify({operation:"spec-rebase",change:t,summary:e,specChanges:i}))}function Ap(t,e,i){return t.phase!=="shape"&&e.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Sp(t){return"implementation_scope"in t?{implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance}:null}function tl(t,e,i,n,r=!1){let a=i.eventData,o=Sp(t),s=Sp(e);if(a.previousPhase!==t.phase||a.nextPhase!==e.phase)throw new Error("Native transition journal event phases do not match its states");if(t.archived||e.archived)throw new Error("Native transition journal cannot mutate an archived change");if(n==="evidence-retreat"){let c=t.name===e.name&&t.language===e.language&&t.brief===e.brief&&t.approval===e.approval&&("approved_contract_hash"in t?"approved_contract_hash"in e&&t.approved_contract_hash===e.approved_contract_hash:!("approved_contract_hash"in e))&&t.created_at===e.created_at&&t.run_id===e.run_id&&Yc(t.spec_changes,e.spec_changes),l=wp({summary:a.summary});if(!(t.phase==="archive"&&t.verification_result==="pass"||t.phase==="verify"&&t.verification_result==="pending")||e.phase!=="build"||e.verification_result!=="pending"||e.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=Qk(t.name,a.summary,e.spec_changes),l=G(`spec-rebase:${t.name}:${a.summary}`);if(t.phase==="shape"||e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||e.verification_report!==null||!r&&i.evidenceHash!==c||r&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in e&&(e.implementation_scope!==null||e.verification_evidence!==null||e.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(t.phase==="shape"){if(e.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||e.verification_result!=="pending"||t.verification_report!==null||e.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(t.phase==="build"){if(e.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||e.verification_result!=="pending"||e.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(t.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||e.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!==a.verificationResult||e.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 Zk(t,e){let i=Ha(t);if(Qc(i,Jk),i.schema!==mi)throw new Error(`Expected Native transition schema ${mi}`);let n=ja(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 ${mi} minimum_runtime_version must be ${3}`);let r=ja(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=Zc(i,e),o=rt(i.previousState),s=rt(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native transition journal state mismatch");if(tl(o,s,a,i.operation),el(o,s,a),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:mi,minimum_runtime_version:3,revision:r,operation:i.operation,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function eE(t,e){let i=Ha(t);if(Qc(i,Wk),i.schema!==Nn)throw new Error(`Expected Native transition schema ${Nn}`);let n=Zc(i,e,!0),r=Rn(i.previousState),a=Rn(i.nextState);if(r.name!==e||a.name!==e)throw new Error("Native transition journal state mismatch");return tl(r,a,n,Ap(r,a,n.eventData),!0),el(r,a,n,!0),{schema:Nn,id:n.id,change:e,evidenceHash:n.evidenceHash,createdAt:n.createdAt,previousState:r,nextState:a,previousRun:n.previousRun,nextRun:n.nextRun,eventData:n.eventData}}function tE(t,e){let i=Ha(t);if(Qc(i,Pp),i.schema!==vi)throw new Error(`Expected Native transition schema ${vi}`);if(ja(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${vi} minimum_runtime_version must be 2`);let r=ja(i.revision,"Native v2 transition revision");if(r!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Zc(i,e,!0),o=Cn(i.previousState),s=Cn(i.nextState);if(o.name!==e||s.name!==e)throw new Error("Native v2 transition journal state mismatch");if(tl(o,s,a,Ap(o,s,a.eventData),!0),el(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:vi,minimum_runtime_version:2,revision:r,id:a.id,change:e,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function iE(t,e){let i=Ha(t);if(i.schema===mi)return{status:"current",journal:Zk(i,e)};if(i.schema===Nn)return{status:"migration-required",journal:eE(i,e)};if(i.schema===vi)return{status:"migration-required",journal:tE(i,e)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function nE(t,e){let i=Xc(t,e);await q(t.nativeRoot,i);try{let n=await tt({root:t.nativeRoot,file:i,maxBytes:Kk,label:`Native transition journal ${e}`});return iE(JSON.parse(n.bytes.toString("utf8")),e)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Jc(t,e){let i=await nE(t,e);if(!i)return null;if(i.status==="migration-required")throw new Gc(e);return i.journal}function kp(t,e){if(Ge(t,e.nextRun))return"next";if(e.previousRun===null){if(t===null)return"previous"}else if(Ge(t,e.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${e.change}; recovery journal was preserved`)}function Ep(t,e){if(Ge(t,e.nextState))return"next";if(Ge(t,e.previousState))return"previous";throw new Error(`Native transition change content changed for ${e.change}; recovery journal was preserved`)}function rE(t){let{journal:e}=t;return xp({sequence:t.sequence,timestamp:e.createdAt,type:t.type,runId:e.nextRun.runId,data:t.type==="run_started"?{runtime:"comet-native",phase:e.previousState.phase,transitionId:e.id}:{...e.eventData,transitionId:e.id}})}function xp(t){return{sequence:t.sequence,timestamp:t.timestamp,type:t.type,runId:t.runId,data:t.data}}function Rp(t,e){let i=t.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===e.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>(e.previousRun===null?1:0)||r.length>1||e.previousRun===null&&r.length===1&&(n.length!==1||n[0].index>=r[0].index))throw new Error(`Native trajectory transition id collision for ${e.change}; recovery journal was preserved`);for(let a of[...n,...r]){let o=rE({sequence:a.index+1,journal:e,type:a.event.type});if(!Ge(xp(a.event),o))throw new Error(`Native trajectory event changed for transition ${e.id}; recovery journal was preserved`)}return{started:n[0]?.event??null,transitioned:r[0]?.event??null}}async function il(t,e,i){if(await Pn(t,e))throw new Error(`Native schema migration is incomplete for ${e}; run doctor --repair`);await va(t,e);let n=await Jc(t,e);if(!n)return null;let r=Y(t,e),a=Rp(await pi(r,n.nextRun.trajectoryRef),n),[o,s]=await Promise.all([yn(r),Ne(t,e)]),c=kp(o,n),l=Ep(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 vc(r,n.nextRun),await i?.afterRunStateWritten?.(n)),!Ge(await yn(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 ya(t,n.nextState,n.previousState.revision);if(!Ge(v,n.nextState))throw new Error(`Native transition change write diverged for ${n.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(n)}if(!Ge(await Ne(t,e),n.nextState))throw new Error(`Native transition change content changed while continuing ${n.change}; recovery journal was preserved`);let u=await Jc(t,e);if(!u||!Ge(u,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was preserved`);let f=Rp(await pi(r,n.nextRun.trajectoryRef),n);n.previousRun===null&&(f.started||await Oa({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 d=f.transitioned;d||(d=await Oa({changeDir:r,run:n.nextRun,type:"state_transitioned",data:{...n.eventData,transitionId:n.id},now:new Date(n.createdAt)})),await Wc({changeDir:r,run:n.nextRun,trajectoryOffset:d.sequence,evidenceHash:n.evidenceHash,now:new Date(n.createdAt)});let[p,m]=await Promise.all([yn(r),Ne(t,e)]);kp(p,{...n,previousRun:n.nextRun}),Ep(m,{...n,previousState:n.nextState});let h=await Jc(t,e);if(!h||!Ge(h,n))throw new Error(`Native transition journal changed while continuing ${n.change}; it was not removed`);return await Vk.rm(Xc(t,e),{force:!0}),n.nextState}async function Tp(t,e,i){let n=await Vh(t,e);if(!n)return null;if(await zh(t,n.change,n.manifest)!==n.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ya(t,n.nextState,n.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(n),await Wh(t,n.checkpoint),await i?.afterProgressWritten?.(n),await aE.rm(Cc(t,e),{force:!0}),n}async function nl(t,e){await il(t,e),await Tp(t,e)}var Ma="scoped-text-safety",oE=1,sE=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var cE="comet.native.checker-policy.v1";var i_=W(cE,{policy:Ma,version:oE,limits:sE,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var lE=["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"],n_=new Set(lE);var f_=512*1024;import Dp from"node:path";import Ip from"node:path";var uE="comet.native.acceptance.v1",fE=/^acceptance-[a-f0-9]{64}$/u,dE=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),hE=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u;var m_=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),On=Object.freeze({maxCriteria:1024}),_n="<!-- comet-native:acceptance-evidence:start -->",bi="<!-- comet-native:acceptance-evidence:end -->";function ol(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function rl(t,e){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!i)return e;let n=i[1][0];return e===null?{marker:n,length:i[1].length}:n===e.marker&&i[1].length>=e.length&&i[2].trim().length===0?null:e}function _p(t){return t.includes("-->")||t.includes("--!>")}function*Si(t){let e=null,i=!1,n=null,r=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
|
|
161
161
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
162
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&n===null,index:s},s+=1,e!==null)e=rl(l,e);else if(i)_p(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=rl(l,null);if(f!==null)e=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!_p(d))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&r.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function
|
|
162
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:e===null&&!i&&n===null,index:s},s+=1,e!==null)e=rl(l,e);else if(i)_p(l)&&(i=!1);else if(n!==null)new RegExp(`</${n}\\s*>`,"iu").test(l)&&(n=null);else{let f=rl(l,null);if(f!==null)e=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!_p(d))i=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&r.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(n=p[1])}}}if(c===-1)break;o=c+1}}function pE(t){return[...Si(t)].map(({line:e,body:i})=>({line:e,body:i}))}function al(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function mE(t){return Array.from(t).some(e=>{let i=e.codePointAt(0)??0;return i<=31||i===127})}function sl(t,e,i,n=[]){let r=al(i),a=e.replaceAll("\\","/").trim(),o=n.map(al);if(r.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(a.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:`acceptance-${W(uE,{kind:t,source:a,context:o,text:r})}`,kind:t,source:a,context:o,text:r}}function cl(t,e){let i=new Set;for(let n of t){if(i.has(n.id))throw new Error(`${e} contains duplicate acceptance criteria`);i.add(n.id)}return t}function vE(t){let e=null,i=null,n=0,r=0;for(let{line:a,body:o,index:s}of Si(t)){r=s+1;let c=o?ol(a):null;c?.level===1&&(c.text.toLocaleLowerCase("en-US")==="acceptance examples"?(n+=1,n===1&&(e=s+1)):e!==null&&i===null&&(i=s))}if(n===0||e===null)return null;if(n!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:i??r}}function Op(t,e="brief.md",i=On.maxCriteria){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=vE(t);if(n===null)return[];let r=null;for(let{line:c,body:l,index:u}of Si(t)){if(u<n.start||u>=n.end)continue;let f=l?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let d=f[1].length;r=r===null?d:Math.min(r,d)}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 Si(t)){if(u<n.start||u>=n.end)continue;let f=l?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===r?(s(),o=[f[2]]):o!==null&&o.push(c)}return s(),cl(a.map(c=>sl("brief-example",e,c.join(`
|
|
163
163
|
`))),"Brief")}function jp(t,e="spec.md",i=On.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(sl("spec-scenario",e,[a.title,...a.body].join(`
|
|
164
|
-
`),a.context)),a=null}};for(let{line:s,body:c}of Si(t)){let l=c?ol(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 f=al(u[1]);if(f.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:f,body:[],context:r.map(d=>d.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(),cl(n,"Specification")}function $p(t,e="spec.md",i=On.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(sl("spec-must",e,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 Si(t)){let f=u?ol(l):null;if(f){for(s(),a!==null&&f.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=f.level;)r.pop();r.push(f),/^Scenario\s*:/iu.test(f.text)&&(a=f.level);continue}let d=l.trim();if(!u||a!==null||c()){s();continue}if(d.length===0||rl(l,null)!==null||d.startsWith("<!--")||d==="-->"||d==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(d)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(d)||/^(?:[-*_]\s*){3,}$/u.test(d)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(d)){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(d)){s(),o={parts:[d],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[d],context:r.map(m=>m.text)}:o.parts.push(d)}return s(),cl(n,"Specification mandatory requirements")}function
|
|
164
|
+
`),a.context)),a=null}};for(let{line:s,body:c}of Si(t)){let l=c?ol(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 f=al(u[1]);if(f.length===0)throw new Error("Scenario title must not be empty");a={level:l.level,title:f,body:[],context:r.map(d=>d.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(),cl(n,"Specification")}function $p(t,e="spec.md",i=On.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(sl("spec-must",e,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 Si(t)){let f=u?ol(l):null;if(f){for(s(),a!==null&&f.level<=a&&(a=null);r.at(-1)&&r.at(-1).level>=f.level;)r.pop();r.push(f),/^Scenario\s*:/iu.test(f.text)&&(a=f.level);continue}let d=l.trim();if(!u||a!==null||c()){s();continue}if(d.length===0||rl(l,null)!==null||d.startsWith("<!--")||d==="-->"||d==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(d)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(d)||/^(?:[-*_]\s*){3,}$/u.test(d)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(d)){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(d)){s(),o={parts:[d],context:r.map(m=>m.text)},s();continue}o===null?o={parts:[d],context:r.map(m=>m.text)}:o.parts.push(d)}return s(),cl(n,"Specification mandatory requirements")}function gE(t,e){let i=t.trim().replaceAll("\\","/");if(i.length===0||mE(i)||Ip.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);let n=Ip.posix.normalize(i);if(n==="."||n===".."||n.startsWith("../"))throw new Error(`Acceptance evidence ${e} has an unsafe evidence ref`);if(n.split("/").some(r=>r.toLowerCase()===".git"||r.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${e} references sensitive content`);if(!hE.test(n))throw new Error(`Acceptance evidence ${e} must reference a content-addressed typed receipt`);return n}function wE(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`Acceptance evidence entry ${e} must be an object`);let i=t,n=Object.keys(i).filter(r=>!dE.has(r));if(n.length>0)throw new Error(`Acceptance evidence entry ${e} has unknown field(s): ${n.join(", ")}`);return i}function Hp(t){if(!Array.isArray(t))throw new Error("Native acceptance evidence block must be a JSON array");let e=new Set;return t.map((i,n)=>{let r=wE(i,n),a=r.acceptance_id;if(typeof a!="string"||!fE.test(a))throw new Error(`Acceptance evidence entry ${n} has an invalid acceptance_id`);if(e.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(e.add(a),!Array.isArray(r.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=r.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return gE(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 ll(t){let e=pE(t);if(e.some(({line:l,body:u})=>!u&&(l===_n||l===bi)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let n=e.flatMap(({line:l,body:u},f)=>u&&l===_n?[f]:[]),r=e.flatMap(({line:l,body:u},f)=>u&&l===bi?[f]:[]);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=e.slice(n[0]+1,r[0]).map(({line:l})=>l).join(`
|
|
165
165
|
`).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=Hp(o),c=Mp(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function Mp(t){let e=Hp([...t]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,n)=>i.acceptance_id.localeCompare(n.acceptance_id));return JSON.stringify(e,null,2)}function Lp(t){return[_n,Mp(t),bi].join(`
|
|
166
|
-
`)}var
|
|
167
|
-
`))}function NE(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.capability))throw new Error(`Invalid Native contract capability: ${t.capability}`);if(t.operation!=="create"&&t.operation!=="replace"&&t.operation!=="remove")throw new Error(`Invalid Native contract operation for ${t.capability}`);if(t.operation==="remove"){if(t.source!==null||t.markdown!==null||!t.baseHash?.match(Fp))throw new Error(`Remove contract ${t.capability} requires only a base hash`);return{snapshot:{capability:t.capability,operation:"remove",source:null,baseHash:t.baseHash,contentHash:null},markdown:null}}if(t.source===null||t.markdown===null)throw new Error(`${t.operation} contract ${t.capability} requires source content`);if(t.operation==="create"&&t.baseHash!==null)throw new Error(`Create contract ${t.capability} requires a null base hash`);if(t.operation==="replace"&&!t.baseHash?.match(Fp))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=Bp(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:qp(t.markdown)},markdown:t.markdown}}function bE(t,e){return Vp(t.id,e.id)}function Vp(t,e){return t<e?-1:t>e?1:0}function zp(t){let e=Bp(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(NE).sort((f,d)=>Vp(f.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:f})=>f.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[e,...i.flatMap(({snapshot:f})=>f.source===null?[]:[f.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=Op(t.briefMarkdown,e,jn.maxAcceptanceCriteria);for(let{snapshot:f,markdown:d}of i)d===null||f.source===null||(a.push(...jp(d,f.source,jn.maxAcceptanceCriteria-a.length)),a.push(...$p(d,f.source,jn.maxAcceptanceCriteria-a.length)));if(a.sort(bE),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:f})=>f);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:e,contentHash:qp(t.briefMarkdown)},c=i.map(({snapshot:f})=>f),l=W(yE,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:W(wE,u)}}var La={maxSpecs:64,maxFileBytes:Fr,maxTotalBytes:4*1024*1024};async function ul(t){if(t.specChanges.length>La.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await Ie({root:t.changeDir,ref:t.briefRef,maxBytes:La.maxFileBytes}),i=e.size,n=[];for(let r of t.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 Ie({root:t.changeDir,ref:r.source,maxBytes:La.maxFileBytes});if(i+=a.size,i>La.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:zp({briefSource:e.ref,briefMarkdown:e.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{createHash as jE}from"node:crypto";import{promises as Fe}from"node:fs";import Ue from"node:path";var Da="comet.native.verification-receipt.v3",Wp=Da,SE="comet.native.declared-artifacts.v1",kE=/^[a-f0-9]{64}$/u,EE=/^acceptance-[a-f0-9]{64}$/u,RE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CE=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,PE=4096,AE=256,xE=1024;function ki(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function _t(t,e,i){let n=Object.keys(t).sort(),r=[...e].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function lt(t,e){if(typeof t!="string"||!kE.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function De(t,e){if(typeof t!="string")throw new Error(`${e} must be text`);let i=Ce(t).trim();if(!i||i.length>PE||i!==t.trim())throw new Error(`${e} is invalid`);return i}function fl(t,e){let i=De(t,e),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${e} must be a canonical timestamp`);return i}function $n(t,e,i=De,n=!1,r=AE){if(!Array.isArray(t)||t.length>r||!n&&t.length===0)throw new Error(`${e} must be a bounded non-empty array`);let a=t.map((o,s)=>i(o,`${e} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${e} has duplicates`);return a}function TE(t,e){if(typeof t!="string"||!EE.test(t))throw new Error(`${e} is invalid`);return t}function IE(t){let e=ki(t,"Native verification receipt bindings");if(_t(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!RE.test(e.change)||!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:e.change,sourceRevision:e.sourceRevision,contractHash:lt(e.contractHash,"Native verification receipt contract hash"),scopeHash:lt(e.scopeHash,"Native verification receipt scope hash"),snapshotHash:lt(e.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:lt(e.artifactHash,"Native verification receipt artifact hash")}}function _E(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=CE.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function OE(t,e,i,n){let r=ki(e,`Native ${t} evidence`);if(t==="automated-check"){if(_t(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=fl(r.startedAt,"Native automated-check start time"),o=fl(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=ki(r.worktree,"Native automated-check worktree");if(_t(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=ki(r.afterFence,"Native automated-check after fence");if(_t(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:De(r.executable,"Native automated-check executable"),args:$n(r.args,"Native automated-check arguments",De,!0),cwd:De(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:De(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:lt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:lt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:lt(r.outputHash,"Native automated-check output hash"),outputSummary:De(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(t==="static-inspection"){_t(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=_E(r.checkReceiptRef);if(lt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:$n(r.subjects,"Native static inspection subjects",De,n==="required-check"),rule:De(r.rule,"Native static inspection rule"),resultSummary:De(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(t==="manual-evidence")return _t(r,["steps","observations"],"Native manual-evidence evidence"),{steps:$n(r.steps,"Native manual evidence steps"),observations:$n(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${t}`)}function Jp(t){let e=ki(t,"Native verification receipt");if(_t(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(e.kind)||e.role!=="required-check"&&e.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(e.status))throw new Error("Native verification receipt kind or status is invalid");let i=e.kind,n=e.role,r=e.status,a=De(e.actor,"Native verification receipt actor"),o=$n(e.acceptanceIds,"Native receipt acceptance IDs",TE,n==="required-check",xE).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:Da,kind:i,role:n,status:r,bindings:IE(e.bindings),acceptanceIds:o,actor:a,issuedAt:fl(e.issuedAt,"Native verification receipt issue time"),evidence:OE(i,e.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ma||s.actor!==`native-runtime:${Ma}`))throw new Error("Native required check policy identity is invalid");return s}function dl(t){let e=Jp({schema:Da,...t});return{...e,receiptHash:W(Wp,e)}}function hl(t){let e=ki(t,"Native verification receipt");if(_t(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==Da)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=e,r=Jp(n),a=lt(e.receiptHash,"Native verification receipt hash");if(W(Wp,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function pl(t){return W(SE,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var Yp=/^[a-f0-9]{64}$/u,Ot=Gt,M_=3*Ot;function ml(t,e){let i=Ue.relative(t,e);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function $E(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fa(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Kp(t){let e=await Fe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${t}`);return{path:t,realPath:await Fe.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function HE(t,e){let i=Ue.resolve(t),n=Ue.resolve(e);if(!ml(i,n))throw new Error("Native evidence path is outside its change");let r=[await Kp(i)],a=i;for(let o of Ue.relative(i,n).split(Ue.sep).filter(Boolean)){a=Ue.join(a,o);let s=await Kp(a);if(!ml(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Gp(t){for(let e of t){let i=await Fe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!$E(e,i)||await Fe.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function ME(t,e,i={}){let n=await HE(e,Ue.dirname(t));await i.afterParentChainCaptured?.();let r=await Fe.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Fe.realpath(t);if(!ml(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Fe.open(t,"r");try{let[s,c,l]=await Promise.all([o.stat(),Fe.lstat(t),Fe.realpath(t)]);if(await Gp(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fa(s,r)||!Fa(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`);await i.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=Ot+1-f,w=await o.read(d,0,Math.min(d.length,v),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,f>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`);u.push(Buffer.from(d.subarray(0,w.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Fe.lstat(t),Fe.realpath(t)]);if(await Gp(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Fa(s,p)||!Fa(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Ba(t,e){if(!Yp.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}async function LE(t,e,i,n,r){if(!Yp.test(i))throw new Error("Native report evidence hash is invalid");let a=await ut({paths:t,name:e,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"||jE("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 Ei(t,e){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(t);if(!i||i[1]!==e)throw new Error(`Native evidence ref is invalid for ${e}`);return i[2]}function Xp(t,e,i,n,r){return Ue.join(r??Y(t,e),...Ba(i,n).split("/"))}async function ut(t){let e=t.changeDir??Y(t.paths,t.name),i=Xp(t.paths,t.name,t.kind,t.hash,e);return await q(t.paths.nativeRoot,i),ME(i,e,t.hooks)}async function DE(t){FE(t.value);let e=Xp(t.paths,t.name,t.kind,t.hash);await q(t.paths.nativeRoot,e);try{let n=await ut(t);if(JSON.stringify(n)!==JSON.stringify(t.value))throw new Error(`Native evidence hash collision for ${t.hash}`);return Ba(t.kind,t.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Oe(e,t.value,{containedRoot:t.paths.nativeRoot});let i=await ut(t);if(JSON.stringify(i)!==JSON.stringify(t.value))throw new Error(`Native evidence changed during commit for ${t.hash}`);return Ba(t.kind,t.hash)}function FE(t){if(BE(t)>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`)}function BE(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
168
|
-
`,"utf8")}function Up(t,e){return Ca(t,e)}function qE(t,e){let i=xa(t);if(i.scopeHash!==e)throw new Error("Native implementation scope ref/hash mismatch");return i}function VE(t,e,i){let n=pp(t);if(n.change!==e||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function zE(t,e,i){let n=Fc(t);if(n.change!==e||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function WE(t,e,i,n=!1,r){let a=await Qp(t,e,i.implementationScopeRef,void 0,r);if(n&&await LE(t,e,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 Zp(t,e,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 qa(t,e,i,n,r){let a=Ei(i,"scopes"),o=qE(await ut({paths:t,name:e,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Ei(o.baselineProjectionRef,"snapshots"),c=Ei(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ut({paths:t,name:e,kind:"snapshots",hash:s,changeDir:r}).then(f=>Up(f,s)),ut({paths:t,name:e,kind:"snapshots",hash:c,changeDir:r}).then(f=>Up(f,c))]);return sp({baseline:l,current:u,scope:o})}async function Qp(t,e,i,n,r){return(await qa(t,e,i,n,r)).scope}async function Zp(t,e,i,n,r){let a=Ei(i,"allowances");return VE(await ut({paths:t,name:e,kind:"allowances",hash:a,hooks:n,changeDir:r}),e,a)}async function vl(t){let e=hl(t.receipt);if(e.bindings.change!==t.name)throw new Error("Native verification receipt change mismatch");return DE({paths:t.paths,name:t.name,kind:"receipts",hash:e.receiptHash,value:e})}async function gl(t,e,i,n,r){let a=Ei(i,"receipts"),o=hl(await ut({paths:t,name:e,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==e||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function wl(t,e,i,n,r){let a=Ei(i,"verifications"),o=zE(await ut({paths:t,name:e,kind:"verifications",hash:a,hooks:n,changeDir:r}),e,a);return await WE(t,e,o,!1,r),o}var Nl=64*1024,UE=12e4,Hn=3600*1e3,YE=4e3,XE="native-runtime:manual-evidence",em=GE(JE),QE=new Set([".bat",".cmd",".ps1"]),ZE=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function eR(t){let e=(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function tR(t,e,i){let r=Ye.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(e.PATH??"").split(Ye.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ye.win32.extname(t)?[t]:eR(e).map(s=>`${t}${s}`);return r.flatMap(s=>o.map(c=>s?Ye.join(s,c):Ye.resolve(i,c)))}function iR(t,e,i){return tR(t,e,i).find(n=>im(n))??t}function nR(t){let e=t.SYSTEMROOT??t.SystemRoot;if(e){let i=Ye.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");if(im(i))return i}return"powershell.exe"}function rR(t,e,i){let n=Buffer.from(JSON.stringify({command:t,arguments:[...e]}),"utf8").toString("base64"),r=Buffer.from(ZE,"utf16le").toString("base64");return yl(nR(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function aR(t,e,i){if(process.platform!=="win32")return yl(t,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=iR(t,i.env,i.cwd);return QE.has(Ye.win32.extname(n).toLowerCase())?rR(n,e,i):yl(n,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function nm(t){return kt(t.paths,t.operation,()=>$a(t.paths,t.name,t.operation,async()=>(await nl(t.paths,t.name),t.issue(await Ne(t.paths,t.name)))))}function oR(t,e){let i=t.trim();if(!i||Buffer.byteLength(i,"utf8")>Nl)throw new Error(`${e} is invalid`);return i}function rm(t,e){let i=[...t].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!e.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Va(t,e){if(e.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${e.phase}`);if(!e.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([qa(t,e.name,e.implementation_scope),ul({changeDir:Y(t,e.name),briefRef:e.brief,specChanges:e.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=e.run_id?`run:${e.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:e.name,sourceRevision:e.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:pl(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var sR=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function bl(t,e){let i=[];for(let n of sR){let r=t.bindings[n],a=e[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function za(t){return nm({paths:t.paths,name:t.name,operation:`issue manual receipt ${t.name}`,issue:e=>cR({...t,state:e})})}async function cR(t){let e=await Va(t.paths,t.state),i=dl({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:e.bindings,acceptanceIds:rm(t.acceptanceIds,e.acceptanceIds),actor:XE,issuedAt:(t.now??new Date).toISOString(),evidence:{steps:[...t.steps],observations:[...t.observations]}});return{receipt:i,ref:await vl({paths:t.paths,name:t.state.name,receipt:i})}}function lR(t){return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...t.capture?{capture:t.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:t.complete,limits:t.limits,...t.policy?{policy:t.policy}:{},entries:t.entries,omitted:t.omitted,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:t.omissionOverflow}:{}}}async function uR(t){let e=lR(t.context.scope.baseline),i=await dc(t.paths,e,{origin:"explicit",now:t.now}),n=Hc({baseline:e,current:i,contractHash:t.context.bindings.contractHash,declaredArtifacts:t.context.scope.scope.declaredArtifacts,noCodeReason:t.context.scope.scope.noCodeReason,gitChangedPaths:t.context.scope.authority.gitChangedPaths});return{snapshotHash:n.scope.currentProjectionHash,scopeHash:n.scope.scopeHash,matched:n.scope.currentProjectionHash===t.context.bindings.snapshotHash&&n.scope.scopeHash===t.context.bindings.scopeHash}}async function tm(t){try{let[{stdout:e},{stdout:i}]=await Promise.all([em("git",["-C",t,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),em("git",["-C",t,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=Ye.resolve(e.trim()),r=Ye.relative(t,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||Ye.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function am(t){return nm({paths:t.paths,name:t.name,operation:`issue automated receipt ${t.name}`,issue:e=>fR({...t,state:e})})}async function fR(t){let e=await Va(t.paths,t.state),i=await tm(t.paths.projectRoot),n=(t.now?.()??new Date).toISOString(),r=t.timeoutMs??UE;if(!Number.isSafeInteger(r)||r<1||r>Hn)throw new Error(`Native automated command timeout must be an integer from 1 through ${Hn}`);let a=[],o=0,s=0,c=KE("sha256"),l=!1,u=aR(t.command,t.args,{cwd:t.paths.projectRoot,env:{...process.env}}),f=g=>{if(c.update(g),s+=g.byteLength,o>=Nl)return;let b=Nl-o,y=g.subarray(0,b);a.push(Buffer.from(y)),o+=y.byteLength};u.stdout.on("data",f),u.stderr.on("data",f);let d=await new Promise((g,b)=>{let y=!1,R=null,O=null,B=D=>{y||(y=!0,clearTimeout(H),O&&clearTimeout(O),g(D))},H=setTimeout(()=>{l=!0,R=Al(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),O=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),B({exitCode:124,signal:"SIGKILL"})},YE)},r);u.once("error",D=>{if(l){(R??Promise.resolve()).then(()=>B({exitCode:124,signal:"SIGKILL"}));return}y||(y=!0,clearTimeout(H),O&&clearTimeout(O),b(D))}),u.once("close",(D,J)=>{(R??Promise.resolve()).then(()=>B({exitCode:l?124:D??1,signal:J??(l?"SIGKILL":null)}))})}),p=(t.now?.()??new Date).toISOString(),[m,h]=await Promise.all([tm(t.paths.projectRoot),uR({paths:t.paths,context:e,now:t.now?.()})]),v=e.scope.current.capture,E=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,k=l||!h.matched||!E?"blocked":d.exitCode===0?"passed":"failed",N=Buffer.concat(a,o).toString("utf8").trim(),S=dl({kind:"automated-check",role:"acceptance-evidence",status:k,bindings:e.bindings,acceptanceIds:rm(t.acceptanceIds,e.acceptanceIds),actor:`native-runtime:command:${t.command}`,issuedAt:p,evidence:{executable:t.command,args:[...t.args],cwd:".",exitCode:d.exitCode,signal:d.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:p,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{...h,matched:h.matched&&E},outputHash:c.digest("hex"),outputSummary:oR(Ce(N||`(exit ${d.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:S,ref:await vl({paths:t.paths,name:t.state.name,receipt:S})}}import dR from"node:path";var hR="Native receipt re-issued after revision bump";function pR(t){return!t.ok&&t.mismatches.length===1&&t.mismatches[0]?.startsWith("sourceRevision: ")===!0}function mR(t){return t.kind!=="automated-check"?"<unknown automated receipt>":[t.evidence.executable,...t.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function vR(t){return`${hR} to revision ${t}`}function gR(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function om(t){let e=await Ne(t.paths,t.name);if(e.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${e.phase} for ${t.name}`);if(!e.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};let i=await Va(t.paths,e),n=await wl(t.paths,t.name,e.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let S of l){let g=await gl(t.paths,t.name,S),b=bl(g,i.bindings);if(!b.ok)if(c.add(S),g.kind==="manual-evidence"){let y={oldRef:S,acceptanceIds:[...g.acceptanceIds]};pR(b)?r.push(y):a.push({...y,mismatches:b.mismatches})}else g.kind==="automated-check"?o.push({oldRef:S,acceptanceIds:[...g.acceptanceIds],command:mR(g),timeoutMs:g.evidence.timeoutMs}):g.kind==="static-inspection"&&s.push({oldRef:S})}if(!(t.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:e.verification_report};let f=[],d=new Map,p=new Map;for(let S of r){let g=[...S.acceptanceIds].sort().join(`
|
|
166
|
+
`)}var yE="comet.native.contract.v1",NE="comet.native.acceptance-set.v1",Fp=/^[a-f0-9]{64}$/u,jn={maxAcceptanceCriteria:On.maxCriteria};function Bp(t,e){let i=Dp.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let r=n.codePointAt(0)??0;return r<=31||r===127})||Dp.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||i!==t||i==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized project-relative ref`);return t}function qp(t){return W("comet.native.contract-content.v1",t.replace(/\r\n?/gu,`
|
|
167
|
+
`))}function bE(t){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.capability))throw new Error(`Invalid Native contract capability: ${t.capability}`);if(t.operation!=="create"&&t.operation!=="replace"&&t.operation!=="remove")throw new Error(`Invalid Native contract operation for ${t.capability}`);if(t.operation==="remove"){if(t.source!==null||t.markdown!==null||!t.baseHash?.match(Fp))throw new Error(`Remove contract ${t.capability} requires only a base hash`);return{snapshot:{capability:t.capability,operation:"remove",source:null,baseHash:t.baseHash,contentHash:null},markdown:null}}if(t.source===null||t.markdown===null)throw new Error(`${t.operation} contract ${t.capability} requires source content`);if(t.operation==="create"&&t.baseHash!==null)throw new Error(`Create contract ${t.capability} requires a null base hash`);if(t.operation==="replace"&&!t.baseHash?.match(Fp))throw new Error(`Replace contract ${t.capability} requires a base hash`);let e=Bp(t.source,`Contract source for ${t.capability}`);return{snapshot:{capability:t.capability,operation:t.operation,source:e,baseHash:t.baseHash,contentHash:qp(t.markdown)},markdown:t.markdown}}function SE(t,e){return Vp(t.id,e.id)}function Vp(t,e){return t<e?-1:t>e?1:0}function zp(t){let e=Bp(t.briefSource??"brief.md","Native brief source"),i=t.specs.map(bE).sort((f,d)=>Vp(f.snapshot.capability,d.snapshot.capability)),n=i.map(({snapshot:f})=>f.capability);if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate capabilities");let r=[e,...i.flatMap(({snapshot:f})=>f.source===null?[]:[f.source])];if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate artifact sources");let a=Op(t.briefMarkdown,e,jn.maxAcceptanceCriteria);for(let{snapshot:f,markdown:d}of i)d===null||f.source===null||(a.push(...jp(d,f.source,jn.maxAcceptanceCriteria-a.length)),a.push(...$p(d,f.source,jn.maxAcceptanceCriteria-a.length)));if(a.sort(SE),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>jn.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${jn.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:f})=>f);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:e,contentHash:qp(t.briefMarkdown)},c=i.map(({snapshot:f})=>f),l=W(NE,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:W(yE,u)}}var La={maxSpecs:64,maxFileBytes:Fr,maxTotalBytes:4*1024*1024};async function ul(t){if(t.specChanges.length>La.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let e=await Ie({root:t.changeDir,ref:t.briefRef,maxBytes:La.maxFileBytes}),i=e.size,n=[];for(let r of t.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 Ie({root:t.changeDir,ref:r.source,maxBytes:La.maxFileBytes});if(i+=a.size,i>La.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:zp({briefSource:e.ref,briefMarkdown:e.text,specs:n}),sourceCount:n.filter(r=>r.source!==null).length+1,totalBytes:i}}import{createHash as $E}from"node:crypto";import{promises as Fe}from"node:fs";import Ue from"node:path";var Da="comet.native.verification-receipt.v3",Wp=Da,kE="comet.native.declared-artifacts.v1",EE=/^[a-f0-9]{64}$/u,RE=/^acceptance-[a-f0-9]{64}$/u,CE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PE=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,AE=4096,xE=256,TE=1024;function ki(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)throw new Error(`${e} must be a plain object`);return t}function _t(t,e,i){let n=Object.keys(t).sort(),r=[...e].sort();if(n.length!==r.length||n.some((a,o)=>a!==r[o]))throw new Error(`${i} fields are invalid`)}function lt(t,e){if(typeof t!="string"||!EE.test(t))throw new Error(`${e} must be a SHA-256 hash`);return t}function De(t,e){if(typeof t!="string")throw new Error(`${e} must be text`);let i=Ce(t).trim();if(!i||i.length>AE||i!==t.trim())throw new Error(`${e} is invalid`);return i}function fl(t,e){let i=De(t,e),n=new Date(i);if(Number.isNaN(n.getTime())||n.toISOString()!==i)throw new Error(`${e} must be a canonical timestamp`);return i}function $n(t,e,i=De,n=!1,r=xE){if(!Array.isArray(t)||t.length>r||!n&&t.length===0)throw new Error(`${e} must be a bounded non-empty array`);let a=t.map((o,s)=>i(o,`${e} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${e} has duplicates`);return a}function IE(t,e){if(typeof t!="string"||!RE.test(t))throw new Error(`${e} is invalid`);return t}function _E(t){let e=ki(t,"Native verification receipt bindings");if(_t(e,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof e.change!="string"||!CE.test(e.change)||!Number.isSafeInteger(e.sourceRevision)||e.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:e.change,sourceRevision:e.sourceRevision,contractHash:lt(e.contractHash,"Native verification receipt contract hash"),scopeHash:lt(e.scopeHash,"Native verification receipt scope hash"),snapshotHash:lt(e.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:lt(e.artifactHash,"Native verification receipt artifact hash")}}function OE(t){if(typeof t!="string")throw new Error("Native static check receipt ref is invalid");let e=PE.exec(t);if(!e)throw new Error("Native static check receipt ref is invalid");return{ref:t,hash:e[1]}}function jE(t,e,i,n){let r=ki(e,`Native ${t} evidence`);if(t==="automated-check"){if(_t(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=fl(r.startedAt,"Native automated-check start time"),o=fl(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=ki(r.worktree,"Native automated-check worktree");if(_t(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=ki(r.afterFence,"Native automated-check after fence");if(_t(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:De(r.executable,"Native automated-check executable"),args:$n(r.args,"Native automated-check arguments",De,!0),cwd:De(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:De(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:lt(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:lt(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:lt(r.outputHash,"Native automated-check output hash"),outputSummary:De(r.outputSummary,"Native automated-check output summary"),outputTruncated:r.outputTruncated}}if(t==="static-inspection"){_t(r,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=OE(r.checkReceiptRef);if(lt(r.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:$n(r.subjects,"Native static inspection subjects",De,n==="required-check"),rule:De(r.rule,"Native static inspection rule"),resultSummary:De(r.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(t==="manual-evidence")return _t(r,["steps","observations"],"Native manual-evidence evidence"),{steps:$n(r.steps,"Native manual evidence steps"),observations:$n(r.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${t}`)}function Jp(t){let e=ki(t,"Native verification receipt");if(_t(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(e.kind)||e.role!=="required-check"&&e.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(e.status))throw new Error("Native verification receipt kind or status is invalid");let i=e.kind,n=e.role,r=e.status,a=De(e.actor,"Native verification receipt actor"),o=$n(e.acceptanceIds,"Native receipt acceptance IDs",IE,n==="required-check",TE).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:Da,kind:i,role:n,status:r,bindings:_E(e.bindings),acceptanceIds:o,actor:a,issuedAt:fl(e.issuedAt,"Native verification receipt issue time"),evidence:jE(i,e.evidence,r,n)};if(n==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Ma||s.actor!==`native-runtime:${Ma}`))throw new Error("Native required check policy identity is invalid");return s}function dl(t){let e=Jp({schema:Da,...t});return{...e,receiptHash:W(Wp,e)}}function hl(t){let e=ki(t,"Native verification receipt");if(_t(e,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),e.schema!==Da)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...n}=e,r=Jp(n),a=lt(e.receiptHash,"Native verification receipt hash");if(W(Wp,r)!==a)throw new Error("Native verification receipt content hash mismatch");return{...r,receiptHash:a}}function pl(t){return W(kE,[...t].map(e=>({path:e.path,kind:e.kind})).sort((e,i)=>e.path.localeCompare(i.path)||e.kind.localeCompare(i.kind)))}var Yp=/^[a-f0-9]{64}$/u,Ot=Gt,L_=3*Ot;function ml(t,e){let i=Ue.relative(t,e);return i===""||!Ue.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ue.sep}`)}function HE(t,e){return F({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fa(t,e){let i={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return se(i,n)?F(i,n):F(i,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Kp(t){let e=await Fe.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${t}`);return{path:t,realPath:await Fe.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function ME(t,e){let i=Ue.resolve(t),n=Ue.resolve(e);if(!ml(i,n))throw new Error("Native evidence path is outside its change");let r=[await Kp(i)],a=i;for(let o of Ue.relative(i,n).split(Ue.sep).filter(Boolean)){a=Ue.join(a,o);let s=await Kp(a);if(!ml(r[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);r.push(s)}return r}async function Gp(t){for(let e of t){let i=await Fe.lstat(e.path);if(!i.isDirectory()||i.isSymbolicLink()||!HE(e,i)||await Fe.realpath(e.path)!==e.realPath)throw new Error(`Native evidence parent changed while reading: ${e.path}`)}}async function LE(t,e,i={}){let n=await ME(e,Ue.dirname(t));await i.afterParentChainCaptured?.();let r=await Fe.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Fe.realpath(t);if(!ml(n[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Fe.open(t,"r");try{let[s,c,l]=await Promise.all([o.stat(),Fe.lstat(t),Fe.realpath(t)]);if(await Gp(n),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!Fa(s,r)||!Fa(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`);await i.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=Ot+1-f,w=await o.read(d,0,Math.min(d.length,v),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,f>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`);u.push(Buffer.from(d.subarray(0,w.bytesRead)))}await i.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Fe.lstat(t),Fe.realpath(t)]);if(await Gp(n),!m.isFile()||m.isSymbolicLink()||h!==a||!Fa(s,p)||!Fa(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Ba(t,e){if(!Yp.test(e))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${t}/${e}.json`}async function DE(t,e,i,n,r){if(!Yp.test(i))throw new Error("Native report evidence hash is invalid");let a=await ut({paths:t,name:e,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"||$E("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 Ei(t,e){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(t);if(!i||i[1]!==e)throw new Error(`Native evidence ref is invalid for ${e}`);return i[2]}function Xp(t,e,i,n,r){return Ue.join(r??Y(t,e),...Ba(i,n).split("/"))}async function ut(t){let e=t.changeDir??Y(t.paths,t.name),i=Xp(t.paths,t.name,t.kind,t.hash,e);return await q(t.paths.nativeRoot,i),LE(i,e,t.hooks)}async function FE(t){BE(t.value);let e=Xp(t.paths,t.name,t.kind,t.hash);await q(t.paths.nativeRoot,e);try{let n=await ut(t);if(JSON.stringify(n)!==JSON.stringify(t.value))throw new Error(`Native evidence hash collision for ${t.hash}`);return Ba(t.kind,t.hash)}catch(n){if(n.code!=="ENOENT")throw n}await Oe(e,t.value,{containedRoot:t.paths.nativeRoot});let i=await ut(t);if(JSON.stringify(i)!==JSON.stringify(t.value))throw new Error(`Native evidence changed during commit for ${t.hash}`);return Ba(t.kind,t.hash)}function BE(t){if(qE(t)>Ot)throw new Error(`Native evidence document exceeds ${Ot} bytes`)}function qE(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
168
|
+
`,"utf8")}function Up(t,e){return Ca(t,e)}function VE(t,e){let i=xa(t);if(i.scopeHash!==e)throw new Error("Native implementation scope ref/hash mismatch");return i}function zE(t,e,i){let n=pp(t);if(n.change!==e||n.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return n}function WE(t,e,i){let n=Fc(t);if(n.change!==e||n.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return n}async function JE(t,e,i,n=!1,r){let a=await Qp(t,e,i.implementationScopeRef,void 0,r);if(n&&await DE(t,e,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 Zp(t,e,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 qa(t,e,i,n,r){let a=Ei(i,"scopes"),o=VE(await ut({paths:t,name:e,kind:"scopes",hash:a,hooks:n,changeDir:r}),a),s=Ei(o.baselineProjectionRef,"snapshots"),c=Ei(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ut({paths:t,name:e,kind:"snapshots",hash:s,changeDir:r}).then(f=>Up(f,s)),ut({paths:t,name:e,kind:"snapshots",hash:c,changeDir:r}).then(f=>Up(f,c))]);return sp({baseline:l,current:u,scope:o})}async function Qp(t,e,i,n,r){return(await qa(t,e,i,n,r)).scope}async function Zp(t,e,i,n,r){let a=Ei(i,"allowances");return zE(await ut({paths:t,name:e,kind:"allowances",hash:a,hooks:n,changeDir:r}),e,a)}async function vl(t){let e=hl(t.receipt);if(e.bindings.change!==t.name)throw new Error("Native verification receipt change mismatch");return FE({paths:t.paths,name:t.name,kind:"receipts",hash:e.receiptHash,value:e})}async function gl(t,e,i,n,r){let a=Ei(i,"receipts"),o=hl(await ut({paths:t,name:e,kind:"receipts",hash:a,hooks:n,changeDir:r}));if(o.bindings.change!==e||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function wl(t,e,i,n,r){let a=Ei(i,"verifications"),o=WE(await ut({paths:t,name:e,kind:"verifications",hash:a,hooks:n,changeDir:r}),e,a);return await JE(t,e,o,!1,r),o}var Nl=64*1024,YE=12e4,Hn=3600*1e3,XE=4e3,QE="native-runtime:manual-evidence",em=UE(KE),ZE=new Set([".bat",".cmd",".ps1"]),eR=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_NATIVE_COMMAND_PAYLOAD","Remove-Item Env:COMET_NATIVE_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function tR(t){let e=(t.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(i=>i.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function iR(t,e,i){let r=Ye.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(e.PATH??"").split(Ye.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ye.win32.extname(t)?[t]:tR(e).map(s=>`${t}${s}`);return r.flatMap(s=>o.map(c=>s?Ye.join(s,c):Ye.resolve(i,c)))}function nR(t,e,i){return iR(t,e,i).find(n=>im(n))??t}function rR(t){let e=t.SYSTEMROOT??t.SystemRoot;if(e){let i=Ye.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");if(im(i))return i}return"powershell.exe"}function aR(t,e,i){let n=Buffer.from(JSON.stringify({command:t,arguments:[...e]}),"utf8").toString("base64"),r=Buffer.from(eR,"utf16le").toString("base64");return yl(rR(i.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",r],{cwd:i.cwd,env:{...i.env,COMET_NATIVE_COMMAND_PAYLOAD:n},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function oR(t,e,i){if(process.platform!=="win32")return yl(t,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=nR(t,i.env,i.cwd);return ZE.has(Ye.win32.extname(n).toLowerCase())?aR(n,e,i):yl(n,[...e],{cwd:i.cwd,env:i.env,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}async function nm(t){return kt(t.paths,t.operation,()=>$a(t.paths,t.name,t.operation,async()=>(await nl(t.paths,t.name),t.issue(await Ne(t.paths,t.name)))))}function sR(t,e){let i=t.trim();if(!i||Buffer.byteLength(i,"utf8")>Nl)throw new Error(`${e} is invalid`);return i}function rm(t,e){let i=[...t].sort();if(i.length===0||new Set(i).size!==i.length||i.some(n=>!e.includes(n)))throw new Error("Native receipt acceptance IDs do not match the current contract");return i}async function Va(t,e){if(e.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${e.phase}`);if(!e.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[i,n]=await Promise.all([qa(t,e.name,e.implementation_scope),ul({changeDir:Y(t,e.name),briefRef:e.brief,specChanges:e.spec_changes})]);if(i.scope.contractHash!==n.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let r=e.run_id?`run:${e.run_id}`:`scope:${i.scope.scopeHash}`;return{bindings:{change:e.name,sourceRevision:e.revision,contractHash:n.contract.contractHash,scopeHash:i.scope.scopeHash,snapshotHash:i.scope.currentProjectionHash,artifactHash:pl(i.scope.declaredArtifacts)},acceptanceIds:n.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${r}`,implementationExecutionId:r,scope:i}}var cR=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function bl(t,e){let i=[];for(let n of cR){let r=t.bindings[n],a=e[n];r!==a&&i.push(`${n}: expected ${JSON.stringify(a)}, got ${JSON.stringify(r)}`)}return{ok:i.length===0,mismatches:i}}async function za(t){return nm({paths:t.paths,name:t.name,operation:`issue manual receipt ${t.name}`,issue:e=>lR({...t,state:e})})}async function lR(t){let e=await Va(t.paths,t.state),i=dl({kind:"manual-evidence",role:"acceptance-evidence",status:"passed",bindings:e.bindings,acceptanceIds:rm(t.acceptanceIds,e.acceptanceIds),actor:QE,issuedAt:(t.now??new Date).toISOString(),evidence:{steps:[...t.steps],observations:[...t.observations]}});return{receipt:i,ref:await vl({paths:t.paths,name:t.state.name,receipt:i})}}function uR(t){return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...t.capture?{capture:t.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:t.complete,limits:t.limits,...t.policy?{policy:t.policy}:{},entries:t.entries,omitted:t.omitted,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:t.omissionOverflow}:{}}}async function fR(t){let e=uR(t.context.scope.baseline),i=await dc(t.paths,e,{origin:"explicit",now:t.now}),n=Hc({baseline:e,current:i,contractHash:t.context.bindings.contractHash,declaredArtifacts:t.context.scope.scope.declaredArtifacts,noCodeReason:t.context.scope.scope.noCodeReason,gitChangedPaths:t.context.scope.authority.gitChangedPaths});return{snapshotHash:n.scope.currentProjectionHash,scopeHash:n.scope.scopeHash,matched:n.scope.currentProjectionHash===t.context.bindings.snapshotHash&&n.scope.scopeHash===t.context.bindings.scopeHash}}async function tm(t){try{let[{stdout:e},{stdout:i}]=await Promise.all([em("git",["-C",t,"rev-parse","--show-toplevel"],{windowsHide:!0,timeout:1e4}),em("git",["-C",t,"rev-parse","HEAD"],{windowsHide:!0,timeout:1e4})]),n=Ye.resolve(e.trim()),r=Ye.relative(t,n).replaceAll("\\","/");if(r===".."||r.startsWith("../")||Ye.posix.isAbsolute(r))throw new Error("Git worktree is outside the Native project root");let a=i.trim().toLowerCase();if(!/^[a-f0-9]{40,64}$/u.test(a))throw new Error("Git commit identity is invalid");return{provider:"git",root:r||".",commit:a}}catch{return{provider:"none",root:".",commit:null}}}async function am(t){return nm({paths:t.paths,name:t.name,operation:`issue automated receipt ${t.name}`,issue:e=>dR({...t,state:e})})}async function dR(t){let e=await Va(t.paths,t.state),i=await tm(t.paths.projectRoot),n=(t.now?.()??new Date).toISOString(),r=t.timeoutMs??YE;if(!Number.isSafeInteger(r)||r<1||r>Hn)throw new Error(`Native automated command timeout must be an integer from 1 through ${Hn}`);let a=[],o=0,s=0,c=GE("sha256"),l=!1,u=oR(t.command,t.args,{cwd:t.paths.projectRoot,env:{...process.env}}),f=g=>{if(c.update(g),s+=g.byteLength,o>=Nl)return;let b=Nl-o,y=g.subarray(0,b);a.push(Buffer.from(y)),o+=y.byteLength};u.stdout.on("data",f),u.stderr.on("data",f);let d=await new Promise((g,b)=>{let y=!1,R=null,O=null,B=D=>{y||(y=!0,clearTimeout(H),O&&clearTimeout(O),g(D))},H=setTimeout(()=>{l=!0,R=Al(u).catch(()=>{u.kill("SIGKILL"),u.stdout?.destroy(),u.stderr?.destroy()}),O=setTimeout(()=>{u.stdout?.destroy(),u.stderr?.destroy(),B({exitCode:124,signal:"SIGKILL"})},XE)},r);u.once("error",D=>{if(l){(R??Promise.resolve()).then(()=>B({exitCode:124,signal:"SIGKILL"}));return}y||(y=!0,clearTimeout(H),O&&clearTimeout(O),b(D))}),u.once("close",(D,J)=>{(R??Promise.resolve()).then(()=>B({exitCode:l?124:D??1,signal:J??(l?"SIGKILL":null)}))})}),p=(t.now?.()??new Date).toISOString(),[m,h]=await Promise.all([tm(t.paths.projectRoot),fR({paths:t.paths,context:e,now:t.now?.()})]),v=e.scope.current.capture,E=(!(v?.provider==="git"||v?.provider==="physical-tree"&&v.projection?.provider==="git")||i.provider==="git")&&i.provider===m.provider&&i.root===m.root&&i.commit===m.commit,k=l||!h.matched||!E?"blocked":d.exitCode===0?"passed":"failed",N=Buffer.concat(a,o).toString("utf8").trim(),S=dl({kind:"automated-check",role:"acceptance-evidence",status:k,bindings:e.bindings,acceptanceIds:rm(t.acceptanceIds,e.acceptanceIds),actor:`native-runtime:command:${t.command}`,issuedAt:p,evidence:{executable:t.command,args:[...t.args],cwd:".",exitCode:d.exitCode,signal:d.signal,timedOut:l,timeoutMs:r,startedAt:n,endedAt:p,worktree:{provider:i.provider,root:i.root,beforeCommit:i.commit,afterCommit:m.commit},afterFence:{...h,matched:h.matched&&E},outputHash:c.digest("hex"),outputSummary:sR(Ce(N||`(exit ${d.exitCode})`),"Native command output summary"),outputTruncated:s>o}});return{receipt:S,ref:await vl({paths:t.paths,name:t.state.name,receipt:S})}}import hR from"node:path";var pR="Native receipt re-issued after revision bump";function mR(t){return!t.ok&&t.mismatches.length===1&&t.mismatches[0]?.startsWith("sourceRevision: ")===!0}function vR(t){return t.kind!=="automated-check"?"<unknown automated receipt>":[t.evidence.executable,...t.evidence.args].map(i=>/\s/u.test(i)?JSON.stringify(i):i).join(" ")}function gR(t){return`${pR} to revision ${t}`}function wR(){return"Manual evidence re-issued via `comet native receipt refresh` to restore revision binding."}async function om(t){let e=await Ne(t.paths,t.name);if(e.phase!=="verify")throw new Error(`Native receipt refresh requires Verify, got ${e.phase} for ${t.name}`);if(!e.verification_evidence)return{refreshed:[],requiresRerun:[],requiresManual:[],requiresCheck:[],applied:!1,verificationReport:null};let i=await Va(t.paths,e),n=await wl(t.paths,t.name,e.verification_evidence),r=[],a=[],o=[],s=[],c=new Set,l=[...new Set([...n.requiredReceiptRefs,...n.receiptRefs])];for(let S of l){let g=await gl(t.paths,t.name,S),b=bl(g,i.bindings);if(!b.ok)if(c.add(S),g.kind==="manual-evidence"){let y={oldRef:S,acceptanceIds:[...g.acceptanceIds]};mR(b)?r.push(y):a.push({...y,mismatches:b.mismatches})}else g.kind==="automated-check"?o.push({oldRef:S,acceptanceIds:[...g.acceptanceIds],command:vR(g),timeoutMs:g.evidence.timeoutMs}):g.kind==="static-inspection"&&s.push({oldRef:S})}if(!(t.apply&&o.length===0&&a.length===0&&r.length>0))return{refreshed:[],requiresRerun:o,requiresManual:a,requiresCheck:s,applied:!1,verificationReport:e.verification_report};let f=[],d=new Map,p=new Map;for(let S of r){let g=[...S.acceptanceIds].sort().join(`
|
|
169
169
|
`),b=p.get(g);b?b.push(S.oldRef):p.set(g,[S.oldRef])}for(let[S,g]of p){let b=S.split(`
|
|
170
|
-
`),y=await za({paths:t.paths,name:t.name,acceptanceIds:b,steps:[
|
|
170
|
+
`),y=await za({paths:t.paths,name:t.name,acceptanceIds:b,steps:[gR(e.revision)],observations:[wR()]});for(let R of b)d.set(R,y.ref);for(let R of g){let O=r.find(B=>B.oldRef===R)?.acceptanceIds[0];O&&f.push({acceptanceId:O,oldRef:R,newRef:y.ref})}}let m=e.verification_report;if(!m)throw new Error(`Native receipt refresh cannot rewrite verification report: ${t.name} has no report ref`);let h=Y(t.paths,t.name),v=await Ie({root:h,ref:m}),w=ll(v.text),E=yR(n.acceptanceTrace.entries,w,c,d),k=Lp(E),N=NR(v.text,k);return await Ze(hR.join(h,...m.split("/")),N),{refreshed:f,requiresRerun:[],requiresManual:[],requiresCheck:s,applied:!0,verificationReport:m}}function yR(t,e,i,n){let r=new Map;for(let o of e)r.set(o.acceptance_id,o);let a=[];for(let o of t){let s=r.get(o.acceptanceId);if(!s)continue;if(o.status==="failed"){a.push(s);continue}let c=s.evidence_refs.filter(d=>!i.has(d)),l=n.get(o.acceptanceId),u=l!==void 0?[...c,l]:c;if(u.length===0){a.push(s);continue}let f={acceptance_id:s.acceptance_id,status:s.status,evidence_refs:[...new Set(u)].sort()};s.skipped_reason!==void 0&&(f.skipped_reason=s.skipped_reason),a.push(f)}return a}function NR(t,e){let i=t.indexOf(_n);if(i<0)throw new Error("Native verification report is missing the acceptance-evidence start marker");let n=t.indexOf(bi,i);if(n<0)throw new Error("Native verification report is missing the acceptance-evidence end marker");let r=t.slice(0,i),a=t.slice(n+bi.length);return`${r}${e}${a}`}import AR from"path";var SR=["Outcome","Scope","Non-goals","Acceptance examples"],CO=[...SR,"Constraints and invariants","Decisions","Open questions","Verification expectations"];var kR=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Wa=class extends Error{details;constructor(e){let i=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=e}};var vj={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var Cj=16*1024*1024,Pj=256*1024,Aj=16*1024;var Ij=16*1024;var qj=16*1024;var x0=16*1024*1024,Ja=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"},Ka=class extends Error{constructor(i,n=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(n);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};var L0=10*1024*1024,pe=class extends Error{};function Mn(t,e){let i=t.flatMap((n,r)=>n===e?[r]:[]);if(i.length>1)throw new pe(`${e} may only be provided once`);return i.length===0?!1:(t.splice(i[0],1),!0)}function Ga(t,e){let i=t.flatMap((a,o)=>a===e?[o]:[]);if(i.length>1)throw new pe(`${e} may only be provided once`);if(i.length===0)return;let n=i[0],r=t[n+1];if(r===void 0||r.startsWith("--"))throw new pe(`${e} requires a value`);return t.splice(n,2),r}function Ln(t,e){let i=[];for(let n=0;n<t.length;){if(t[n]!==e){n+=1;continue}let r=t[n+1];if(r===void 0||r.startsWith("--"))throw new pe(`${e} requires a value`);i.push(r),t.splice(n,2)}return i}function Ua(t){if(t.length>0)throw new pe(`Unexpected argument: ${t[0]}`)}function Sl(t,e){let i=t.shift();if(!i||i.startsWith("--"))throw new pe(`${e} is required`);return i}async function sm(t){return t?AR.resolve(t):Qr(process.cwd())}async function cm(t){let e=await _d({startPath:t,allowMissingConfig:!1});return{config:e.config,paths:e.paths}}function kl(t,e,i){return{command:t,exitCode:0,data:e,text:i??JSON.stringify(e,null,2)+`
|
|
171
171
|
`}}function lm(t,e){if(e instanceof pe)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof Ja)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof Ka)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof Sn)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof ga)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:e.message}};if(e instanceof Wa)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Error){let i=e.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function um(t,e){return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
172
172
|
`}:t.error?{exitCode:t.exitCode,stderr:t.error.message}:{exitCode:t.exitCode,stdout:t.text}}async function fm(t,e){let i=Sl(t,"receipt subcommand"),n=Sl(t,"change name"),{paths:r}=await cm(e);if(i==="manual"){let a=Ln(t,"--acceptance"),o=Ln(t,"--step"),s=Ln(t,"--observation");Ua(t);let c=await za({paths:r,name:n,acceptanceIds:a,steps:o,observations:s});return kl("receipt manual",c,`Native manual receipt: ${c.ref}
|
|
173
173
|
`)}if(i==="automated"){let a=t.indexOf("--");if(a<0||a===t.length-1)throw new pe("receipt automated requires -- <executable> [args...]");let o=t.splice(a+1);t.splice(a,1);let s=Ln(t,"--acceptance"),c=Ga(t,"--timeout-ms");Ua(t);let l=c===void 0?void 0:/^[1-9]\d*$/u.test(c)&&Number.isSafeInteger(Number(c))&&Number(c)<=Hn?Number(c):null;if(l===null)throw new pe(`--timeout-ms must be an integer from 1 through ${Hn}`);let u=await am({paths:r,name:n,acceptanceIds:s,command:o[0],args:o.slice(1),...l===void 0?{}:{timeoutMs:l}});return{command:"receipt automated",exitCode:u.receipt.status==="passed"?0:1,data:u,text:`Native automated receipt ${u.receipt.status}: ${u.ref}
|
|
174
174
|
`}}if(i==="refresh"){let a=Mn(t,"--apply"),o=Mn(t,"--dry-run");if(Ua(t),a&&o)throw new pe("receipt refresh --apply and --dry-run cannot be combined");let s=await om({paths:r,name:n,apply:a}),c=[];if(s.refreshed.length>0){c.push(`Re-issued ${s.refreshed.length} manual receipt(s) at the current revision:`);for(let l of s.refreshed)c.push(` ${l.acceptanceId}: ${l.oldRef} -> ${l.newRef}`)}if(s.requiresRerun.length>0){c.push(`Re-run ${s.requiresRerun.length} stale automated receipt(s) (they cannot be re-issued without a real execution):`);for(let l of s.requiresRerun){let u=l.acceptanceIds.join(", ");c.push(` [${u}] ${l.command}`)}}if(s.requiresManual.length>0){c.push(`Re-run manual verification for ${s.requiresManual.length} receipt(s); contract, scope, snapshot, or artifact bindings changed:`);for(let l of s.requiresManual)c.push(` [${l.acceptanceIds.join(", ")}] ${l.mismatches.join("; ")}`)}return s.requiresCheck.length>0&&c.push(`Re-run \`comet native check ${n}\` to refresh ${s.requiresCheck.length} required-check receipt(s).`),s.applied?c.push(`Updated acceptance evidence in ${s.verificationReport}.`):s.refreshed.length===0&&s.requiresRerun.length===0&&s.requiresManual.length===0&&s.requiresCheck.length===0?c.push("No stale receipts found."):a?s.requiresManual.length>0&&c.push("Fresh manual verification is required before these receipts can be refreshed."):c.push("Dry run only. Re-run with --apply to re-issue manual receipts."),kl("receipt refresh",s,`${c.join(`
|
|
175
175
|
`)}
|
|
176
|
-
`)}throw new pe(`Unknown receipt command: ${i}`)}function
|
|
177
|
-
`}}async function dm(t,e,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{Mn(r,"--json"),s=Ga(r,"--project-root");let u=[...r,...a],f=await sm(s);c=await e(u,f)}catch(u){c=lm(t,u)}let l=o?
|
|
176
|
+
`)}throw new pe(`Unknown receipt command: ${i}`)}function xR(t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
|
|
177
|
+
`}}async function dm(t,e,i=process.argv.slice(2)){let n=i.indexOf("--"),r=n<0?[...i]:i.slice(0,n),a=n<0?[]:i.slice(n),o=r.includes("--json"),s,c;try{Mn(r,"--json"),s=Ga(r,"--project-root");let u=[...r,...a],f=await sm(s);c=await e(u,f)}catch(u){c=lm(t,u)}let l=o?xR(c):um(c,!1);return l.stdout&&process.stdout.write(l.stdout),l.stderr&&process.stderr.write(l.stderr+(l.stderr.endsWith(`
|
|
178
178
|
`)?"":`
|
|
179
179
|
`)),l.exitCode}process.exitCode=await dm("receipt",fm);
|