@rpamis/comet 0.4.0-rc.6 → 0.4.0
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/LICENSE +21 -21
- package/README.md +332 -333
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +56 -51
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +22 -20
- package/assets/skills/comet/scripts/comet-guard.mjs +93 -88
- package/assets/skills/comet/scripts/comet-handoff.mjs +111 -106
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +54 -49
- package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
- package/assets/skills/comet/scripts/comet-intent.mjs +12 -7
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +50 -45
- package/assets/skills/comet/scripts/comet-runtime.mjs +180 -175
- package/assets/skills/comet/scripts/comet-state.mjs +80 -75
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +57 -52
- package/assets/skills/comet-classic/reference/scripts.md +1 -1
- package/assets/skills/comet-native/SKILL.md +3 -3
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +51 -51
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +37 -37
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +33 -33
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +43 -43
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +71 -71
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +36 -36
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +27 -27
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +23 -23
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
- package/assets/skills-zh/comet-classic/reference/scripts.md +1 -1
- package/assets/skills-zh/comet-native/SKILL.md +3 -3
- package/bin/fast-runtime-router.js +1 -1
- package/dist/app/cli/index.js +7 -1
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/classic.js +4 -0
- package/dist/app/commands/classic.js.map +1 -1
- package/dist/app/commands/doctor.d.ts +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +2 -1
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/eval.js +2 -2
- package/dist/app/commands/eval.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +16 -5
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/personal-memory.d.ts.map +1 -1
- package/dist/app/commands/personal-memory.js +5 -0
- package/dist/app/commands/personal-memory.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +26 -2
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/app/commands/status.d.ts.map +1 -1
- package/dist/app/commands/status.js +17 -10
- package/dist/app/commands/status.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +5 -1
- 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 +10 -4
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
- package/dist/domains/agent-learning/context-director.js +14 -10
- package/dist/domains/agent-learning/context-director.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive.js +3 -0
- package/dist/domains/comet-classic/classic-archive.js.map +1 -1
- package/dist/domains/comet-classic/classic-cli-help.d.ts +3 -0
- package/dist/domains/comet-classic/classic-cli-help.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-cli-help.js +40 -0
- package/dist/domains/comet-classic/classic-cli-help.js.map +1 -0
- package/dist/domains/comet-classic/classic-cli.d.ts +1 -0
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +5 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +12 -2
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.js +11 -10
- package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +4 -1
- package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +37 -18
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.js +2 -0
- package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace.d.ts +1 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-workspace.js +2 -1
- package/dist/domains/comet-classic/classic-workspace.js.map +1 -1
- package/dist/domains/comet-entry/entry-runtime.d.ts.map +1 -1
- package/dist/domains/comet-entry/entry-runtime.js +13 -3
- package/dist/domains/comet-entry/entry-runtime.js.map +1 -1
- package/dist/domains/comet-memory/plugin.js +4 -9
- package/dist/domains/comet-memory/plugin.js.map +1 -1
- package/dist/domains/comet-memory/repository.d.ts +3 -0
- package/dist/domains/comet-memory/repository.d.ts.map +1 -1
- package/dist/domains/comet-memory/repository.js +117 -25
- package/dist/domains/comet-memory/repository.js.map +1 -1
- package/dist/domains/comet-memory/review-contract.d.ts.map +1 -1
- package/dist/domains/comet-memory/review-contract.js +4 -2
- package/dist/domains/comet-memory/review-contract.js.map +1 -1
- package/dist/domains/comet-native/native-check-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check-command.js +5 -1
- package/dist/domains/comet-native/native-check-command.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +7 -2
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +22 -1
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js +3 -1
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +11 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +14 -8
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.d.ts +2 -2
- package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.js +89 -77
- package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
- package/dist/domains/comet-plugin/types.d.ts +2 -0
- package/dist/domains/comet-plugin/types.d.ts.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +20 -0
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/web/index.html +14 -14
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +4 -3
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.js +2 -2
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +5 -2
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/skill/languages.d.ts +3 -1
- package/dist/domains/skill/languages.d.ts.map +1 -1
- package/dist/domains/skill/languages.js +26 -1
- package/dist/domains/skill/languages.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +16 -0
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/platform/process/git-environment.d.ts +3 -0
- package/dist/platform/process/git-environment.d.ts.map +1 -0
- package/dist/platform/process/git-environment.js +26 -0
- package/dist/platform/process/git-environment.js.map +1 -0
- package/eval/langsmith/tests/tasks/test_tasks.py +6 -0
- package/eval/local/tests/scaffold/test_langsmith_conftest.py +10 -0
- package/package.json +2 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var oj=Object.create;var Vp=Object.defineProperty;var sj=Object.getOwnPropertyDescriptor;var cj=Object.getOwnPropertyNames;var lj=Object.getPrototypeOf,uj=Object.prototype.hasOwnProperty;var Zu=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var _=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ed=(e,t)=>{for(var r in t)Vp(e,r,{get:t[r],enumerable:!0})},dj=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of cj(t))!uj.call(e,n)&&n!==r&&Vp(e,n,{get:()=>t[n],enumerable:!(i=sj(t,n))||i.enumerable});return e};var Ha=(e,t,r)=>(r=e!=null?oj(lj(e)):{},dj(t||!e||!e.__esModule?Vp(r,"default",{value:e,enumerable:!0}):r,e));import{execFileSync as fj}from"child_process";import wc from"path";function xn(e,t){return fj("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function hj(e,t){let r=wc.normalize(e),i=wc.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ne(e){try{let t=wc.resolve(xn(e,["rev-parse","--show-toplevel"])),i=xn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?wc.resolve(i.slice(9)):t,a=null;try{a=xn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!hj(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function td(e){try{xn(e,["rev-parse","--is-inside-work-tree"]);let t=xn(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:wc.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function kt(e){return td(e).map(t=>t.root)}function An(e,t){try{return xn(e,["check-ref-format","--branch",t]),xn(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function
|
|
5
|
-
`,r)}var $e=_(()=>{"use strict";Ir()});import Wp from"path";function kj(e){return e.toLowerCase().startsWith(".env")}function yi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>kj(i))?"environment-file":r.some(i=>bj.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Nj.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function zp(e,t){let r=yi(t);if(r)return r;let i=Wp.resolve(e.projectRoot,...t.split("/")),n=Wp.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===Wp.resolve(e.configFile)?"native-runtime":null}var Nj,bj,Nc=_(()=>{"use strict";Nj=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),bj=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Sj}from"node:crypto";import{promises as Qr}from"node:fs";import Tr from"node:path";import{TextDecoder as Ej}from"node:util";function Jp(e,t){let r=Tr.relative(e,t);return r===""||!Tr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Tr.sep}`)}function Rj(e){let t=Tr.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Tr.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=yi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function Pj(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Cj(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function UN(e){let t=await Qr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Qr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function xj(e,t){let r=Tr.resolve(e),i=Tr.resolve(t);if(!Jp(r,i))throw new Error("Native artifact path is outside its root");let n=[await UN(r)],a=r;for(let o of Tr.relative(r,i).split(Tr.sep).filter(Boolean)){a=Tr.join(a,o);let s=await UN(a);if(!Jp(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function KN(e){for(let t of e){let r=await Qr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Cj(t,r)||await Qr.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=Rj(e.ref),r=e.maxBytes===null?null:Pj(e.maxBytes??bc),i=Tr.resolve(e.root,...t.split("/")),n=await xj(e.root,Tr.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Qr.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Qr.realpath(i);if(!Jp(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Qr.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),Qr.lstat(i),Qr.realpath(i)]);if(await KN(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!nd(a,c)||!nd(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let S=r===null?p.length:r+1-f,N=await s.read(p,0,Math.min(p.length,S),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Qr.lstat(i),Qr.realpath(i)]);if(await KN(n),!h.isFile()||h.isSymbolicLink()||m!==o||!nd(c,v)||!nd(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),w;try{w=new Ej("utf-8",{fatal:!0}).decode(g)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:Sj("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var bc,Jt=_(()=>{"use strict";Nc();Ir();bc=1024*1024});var le=x(St=>{"use strict";var Gp=Symbol.for("yaml.alias"),YN=Symbol.for("yaml.document"),ad=Symbol.for("yaml.map"),XN=Symbol.for("yaml.pair"),Up=Symbol.for("yaml.scalar"),od=Symbol.for("yaml.seq"),Wi=Symbol.for("yaml.node.type"),Aj=e=>!!e&&typeof e=="object"&&e[Wi]===Gp,_j=e=>!!e&&typeof e=="object"&&e[Wi]===YN,Ij=e=>!!e&&typeof e=="object"&&e[Wi]===ad,Tj=e=>!!e&&typeof e=="object"&&e[Wi]===XN,QN=e=>!!e&&typeof e=="object"&&e[Wi]===Up,jj=e=>!!e&&typeof e=="object"&&e[Wi]===od;function ZN(e){if(e&&typeof e=="object")switch(e[Wi]){case ad:case od:return!0}return!1}function $j(e){if(e&&typeof e=="object")switch(e[Wi]){case Gp:case ad:case Up:case od:return!0}return!1}var Oj=e=>(QN(e)||ZN(e))&&!!e.anchor;St.ALIAS=Gp;St.DOC=YN;St.MAP=ad;St.NODE_TYPE=Wi;St.PAIR=XN;St.SCALAR=Up;St.SEQ=od;St.hasAnchor=Oj;St.isAlias=Aj;St.isCollection=ZN;St.isDocument=_j;St.isMap=Ij;St.isNode=$j;St.isPair=Tj;St.isScalar=QN;St.isSeq=jj});var kc=x(Kp=>{"use strict";var st=le(),nr=Symbol("break visit"),eb=Symbol("skip children"),Ni=Symbol("remove node");function sd(e,t){let r=tb(t);st.isDocument(e)?Wo(null,e.contents,r,Object.freeze([e]))===Ni&&(e.contents=null):Wo(null,e,r,Object.freeze([]))}sd.BREAK=nr;sd.SKIP=eb;sd.REMOVE=Ni;function Wo(e,t,r,i){let n=rb(e,t,r,i);if(st.isNode(n)||st.isPair(n))return ib(e,i,n),Wo(e,n,r,i);if(typeof n!="symbol"){if(st.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Wo(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===nr)return nr;o===Ni&&(t.items.splice(a,1),a-=1)}}}else if(st.isPair(t)){i=Object.freeze(i.concat(t));let a=Wo("key",t.key,r,i);if(a===nr)return nr;a===Ni&&(t.key=null);let o=Wo("value",t.value,r,i);if(o===nr)return nr;o===Ni&&(t.value=null)}}return n}async function cd(e,t){let r=tb(t);st.isDocument(e)?await zo(null,e.contents,r,Object.freeze([e]))===Ni&&(e.contents=null):await zo(null,e,r,Object.freeze([]))}cd.BREAK=nr;cd.SKIP=eb;cd.REMOVE=Ni;async function zo(e,t,r,i){let n=await rb(e,t,r,i);if(st.isNode(n)||st.isPair(n))return ib(e,i,n),zo(e,n,r,i);if(typeof n!="symbol"){if(st.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await zo(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===nr)return nr;o===Ni&&(t.items.splice(a,1),a-=1)}}}else if(st.isPair(t)){i=Object.freeze(i.concat(t));let a=await zo("key",t.key,r,i);if(a===nr)return nr;a===Ni&&(t.key=null);let o=await zo("value",t.value,r,i);if(o===nr)return nr;o===Ni&&(t.value=null)}}return n}function tb(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function rb(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(st.isMap(t))return r.Map?.(e,t,i);if(st.isSeq(t))return r.Seq?.(e,t,i);if(st.isPair(t))return r.Pair?.(e,t,i);if(st.isScalar(t))return r.Scalar?.(e,t,i);if(st.isAlias(t))return r.Alias?.(e,t,i)}function ib(e,t,r){let i=t[t.length-1];if(st.isCollection(i))i.items[e]=r;else if(st.isPair(i))e==="key"?i.key=r:i.value=r;else if(st.isDocument(i))i.contents=r;else{let n=st.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Kp.visit=sd;Kp.visitAsync=cd});var Yp=x(ab=>{"use strict";var nb=le(),Hj=kc(),Dj={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bj=e=>e.replace(/[!,[\]{}]/g,t=>Dj[t]),Sc=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Bj(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&nb.isNode(t.contents)){let a={};Hj.visit(t.contents,(o,s)=>{nb.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
6
|
-
`)}};Sc.defaultYaml={explicit:!1,version:"1.2"};Sc.defaultTags={"!!":"tag:yaml.org,2002:"};ab.Directives=Sc});var ld=x(Ec=>{"use strict";var ob=le(),qj=kc();function Fj(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function sb(e){let t=new Set;return qj.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function cb(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Mj(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=sb(e));let o=cb(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(ob.isScalar(o.node)||ob.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Ec.anchorIsValid=Fj;Ec.anchorNames=sb;Ec.createNodeAnchors=Mj;Ec.findNewAnchor=cb});var Xp=x(lb=>{"use strict";function Rc(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Rc(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Rc(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Rc(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Rc(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}lb.applyReviver=Rc});var In=x(db=>{"use strict";var Lj=le();function ub(e,t,r){if(Array.isArray(e))return e.map((i,n)=>ub(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Lj.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}db.toJS=ub});var ud=x(hb=>{"use strict";var Vj=Xp(),fb=le(),Wj=In(),Qp=class{constructor(t){Object.defineProperty(this,fb.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!fb.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Wj.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Vj.applyReviver(a,{"":s},"",s):s}};hb.NodeBase=Qp});var Pc=x(pb=>{"use strict";var zj=ld(),Jj=kc(),Jo=le(),Gj=ud(),Uj=In(),Zp=class extends Gj.NodeBase{constructor(t){super(Jo.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Jj.visit(t,{Node:(a,o)=>{(Jo.isAlias(o)||Jo.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Uj.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=dd(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(zj.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function dd(e,t,r){if(Jo.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Jo.isCollection(t)){let i=0;for(let n of t.items){let a=dd(e,n,r);a>i&&(i=a)}return i}else if(Jo.isPair(t)){let i=dd(e,t.key,r),n=dd(e,t.value,r);return Math.max(i,n)}return 1}pb.Alias=Zp});var et=x(em=>{"use strict";var Kj=le(),Yj=ud(),Xj=In(),Qj=e=>!e||typeof e!="function"&&typeof e!="object",Tn=class extends Yj.NodeBase{constructor(t){super(Kj.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Xj.toJS(this.value,t,r)}toString(){return String(this.value)}};Tn.BLOCK_FOLDED="BLOCK_FOLDED";Tn.BLOCK_LITERAL="BLOCK_LITERAL";Tn.PLAIN="PLAIN";Tn.QUOTE_DOUBLE="QUOTE_DOUBLE";Tn.QUOTE_SINGLE="QUOTE_SINGLE";em.Scalar=Tn;em.isScalarValue=Qj});var Cc=x(vb=>{"use strict";var Zj=Pc(),Da=le(),mb=et(),e$="tag:yaml.org,2002:";function t$(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function r$(e,t,r){if(Da.isDocument(e)&&(e=e.contents),Da.isNode(e))return e;if(Da.isPair(e)){let d=r.schema[Da.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Zj.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=e$+t.slice(2));let l=t$(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new mb.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Da.MAP]:Symbol.iterator in Object(e)?o[Da.SEQ]:o[Da.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new mb.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}vb.createNode=r$});var hd=x(fd=>{"use strict";var i$=Cc(),
|
|
4
|
+
var oj=Object.create;var Vp=Object.defineProperty;var sj=Object.getOwnPropertyDescriptor;var cj=Object.getOwnPropertyNames;var lj=Object.getPrototypeOf,uj=Object.prototype.hasOwnProperty;var Zu=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var _=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ed=(e,t)=>{for(var r in t)Vp(e,r,{get:t[r],enumerable:!0})},dj=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of cj(t))!uj.call(e,n)&&n!==r&&Vp(e,n,{get:()=>t[n],enumerable:!(i=sj(t,n))||i.enumerable});return e};var Ha=(e,t,r)=>(r=e!=null?oj(lj(e)):{},dj(t||!e||!e.__esModule?Vp(r,"default",{value:e,enumerable:!0}):r,e));import{execFileSync as fj}from"child_process";import wc from"path";function xn(e,t){return fj("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function hj(e,t){let r=wc.normalize(e),i=wc.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ne(e){try{let t=wc.resolve(xn(e,["rev-parse","--show-toplevel"])),i=xn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?wc.resolve(i.slice(9)):t,a=null;try{a=xn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!hj(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function td(e){try{xn(e,["rev-parse","--is-inside-work-tree"]);let t=xn(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:wc.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function kt(e){return td(e).map(t=>t.root)}function An(e,t){try{return xn(e,["check-ref-format","--branch",t]),xn(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function yi(e,t){try{let r=xn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var zt=_(()=>{"use strict"});function _n(e){return e!==0&&e!==0n&&e!=="0"}function wr(e,t){return _n(e.dev)&&_n(t.dev)&&_n(e.ino)&&_n(t.ino)}function J(e,t){let r=_n(e.dev)&&_n(t.dev);if(r&&e.dev!==t.dev)return!1;let i=_n(e.ino)&&_n(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var yc=_(()=>{"use strict"});var Ir=_(()=>{"use strict";yc()});import{randomUUID as pj}from"crypto";import{promises as ft}from"fs";import Qr from"path";function rd(e,t){let r=Qr.relative(e,t);return r===""||!Qr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Qr.sep}`)}function mj(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function id(e,t){return J({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function vj(e,t){return id(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zN(e){let t=await ft.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ft.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Vo(e){for(let t of e){let r=await ft.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!mj(t,r)||await ft.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function gj(e,t,r){let[i,n]=await Promise.all([ft.lstat(e),ft.realpath(e),r?Vo(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!id(i,t)||r&&!rd(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function wj(e,t){let r=Qr.resolve(e),i=Qr.resolve(t);if(!rd(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await zN(r)],a=Qr.relative(r,i).split(Qr.sep).filter(Boolean),o=r;for(let s of a){await Vo(n),o=Qr.join(o,s);try{await ft.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zN(o);if(!rd(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Vo(n),n}async function yj(e){let t;try{t=await ft.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function JN(e,t,r={}){let i=Qr.dirname(e),n=r.containedRoot?await wj(r.containedRoot,i):null;n||await ft.mkdir(i,{recursive:!0});let a=Qr.join(i,`.${Qr.basename(e)}.${pj()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ft.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([ft.lstat(a),ft.realpath(a)]);if(await Vo(n),!l.isFile()||l.isSymbolicLink()||!id(s,l)||!rd(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!id(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await gj(a,c,n),await r.beforeCommit?.(),n){await Vo(n);let l=await ft.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!vj(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ft.link(a,e),await ft.unlink(a)):await ft.rename(a,e),await yj(i)}catch(l){if(await o?.close(),!n)await ft.rm(a,{force:!0});else try{await Vo(n),await ft.rm(a,{force:!0})}catch{}throw l}}async function xe(e,t,r={}){await JN(e,t,r)}async function GN(e,t,r={}){await JN(e,t,r)}async function fe(e,t,r={}){await xe(e,JSON.stringify(t,null,2)+`
|
|
5
|
+
`,r)}var Oe=_(()=>{"use strict";Ir()});import Wp from"path";function kj(e){return e.toLowerCase().startsWith(".env")}function Ni(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>kj(i))?"environment-file":r.some(i=>bj.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Nj.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function zp(e,t){let r=Ni(t);if(r)return r;let i=Wp.resolve(e.projectRoot,...t.split("/")),n=Wp.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===Wp.resolve(e.configFile)?"native-runtime":null}var Nj,bj,Nc=_(()=>{"use strict";Nj=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),bj=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Sj}from"node:crypto";import{promises as Zr}from"node:fs";import Tr from"node:path";import{TextDecoder as Ej}from"node:util";function Jp(e,t){let r=Tr.relative(e,t);return r===""||!Tr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Tr.sep}`)}function Rj(e){let t=Tr.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Tr.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Ni(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function Pj(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Cj(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function nd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function UN(e){let t=await Zr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Zr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function xj(e,t){let r=Tr.resolve(e),i=Tr.resolve(t);if(!Jp(r,i))throw new Error("Native artifact path is outside its root");let n=[await UN(r)],a=r;for(let o of Tr.relative(r,i).split(Tr.sep).filter(Boolean)){a=Tr.join(a,o);let s=await UN(a);if(!Jp(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function KN(e){for(let t of e){let r=await Zr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Cj(t,r)||await Zr.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function re(e){let t=Rj(e.ref),r=e.maxBytes===null?null:Pj(e.maxBytes??bc),i=Tr.resolve(e.root,...t.split("/")),n=await xj(e.root,Tr.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Zr.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Zr.realpath(i);if(!Jp(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Zr.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),Zr.lstat(i),Zr.realpath(i)]);if(await KN(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!nd(a,c)||!nd(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let S=r===null?p.length:r+1-f,N=await s.read(p,0,Math.min(p.length,S),null);if(N.bytesRead===0)break;if(f+=N.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,N.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Zr.lstat(i),Zr.realpath(i)]);if(await KN(n),!h.isFile()||h.isSymbolicLink()||m!==o||!nd(c,v)||!nd(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),w;try{w=new Ej("utf-8",{fatal:!0}).decode(g)}catch(S){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:S})}return{ref:t,size:f,hash:e.includeHash===!1?null:Sj("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var bc,Jt=_(()=>{"use strict";Nc();Ir();bc=1024*1024});var le=x(St=>{"use strict";var Gp=Symbol.for("yaml.alias"),YN=Symbol.for("yaml.document"),ad=Symbol.for("yaml.map"),XN=Symbol.for("yaml.pair"),Up=Symbol.for("yaml.scalar"),od=Symbol.for("yaml.seq"),zi=Symbol.for("yaml.node.type"),Aj=e=>!!e&&typeof e=="object"&&e[zi]===Gp,_j=e=>!!e&&typeof e=="object"&&e[zi]===YN,Ij=e=>!!e&&typeof e=="object"&&e[zi]===ad,Tj=e=>!!e&&typeof e=="object"&&e[zi]===XN,QN=e=>!!e&&typeof e=="object"&&e[zi]===Up,jj=e=>!!e&&typeof e=="object"&&e[zi]===od;function ZN(e){if(e&&typeof e=="object")switch(e[zi]){case ad:case od:return!0}return!1}function $j(e){if(e&&typeof e=="object")switch(e[zi]){case Gp:case ad:case Up:case od:return!0}return!1}var Oj=e=>(QN(e)||ZN(e))&&!!e.anchor;St.ALIAS=Gp;St.DOC=YN;St.MAP=ad;St.NODE_TYPE=zi;St.PAIR=XN;St.SCALAR=Up;St.SEQ=od;St.hasAnchor=Oj;St.isAlias=Aj;St.isCollection=ZN;St.isDocument=_j;St.isMap=Ij;St.isNode=$j;St.isPair=Tj;St.isScalar=QN;St.isSeq=jj});var kc=x(Kp=>{"use strict";var st=le(),nr=Symbol("break visit"),eb=Symbol("skip children"),bi=Symbol("remove node");function sd(e,t){let r=tb(t);st.isDocument(e)?Wo(null,e.contents,r,Object.freeze([e]))===bi&&(e.contents=null):Wo(null,e,r,Object.freeze([]))}sd.BREAK=nr;sd.SKIP=eb;sd.REMOVE=bi;function Wo(e,t,r,i){let n=rb(e,t,r,i);if(st.isNode(n)||st.isPair(n))return ib(e,i,n),Wo(e,n,r,i);if(typeof n!="symbol"){if(st.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Wo(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===nr)return nr;o===bi&&(t.items.splice(a,1),a-=1)}}}else if(st.isPair(t)){i=Object.freeze(i.concat(t));let a=Wo("key",t.key,r,i);if(a===nr)return nr;a===bi&&(t.key=null);let o=Wo("value",t.value,r,i);if(o===nr)return nr;o===bi&&(t.value=null)}}return n}async function cd(e,t){let r=tb(t);st.isDocument(e)?await zo(null,e.contents,r,Object.freeze([e]))===bi&&(e.contents=null):await zo(null,e,r,Object.freeze([]))}cd.BREAK=nr;cd.SKIP=eb;cd.REMOVE=bi;async function zo(e,t,r,i){let n=await rb(e,t,r,i);if(st.isNode(n)||st.isPair(n))return ib(e,i,n),zo(e,n,r,i);if(typeof n!="symbol"){if(st.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await zo(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===nr)return nr;o===bi&&(t.items.splice(a,1),a-=1)}}}else if(st.isPair(t)){i=Object.freeze(i.concat(t));let a=await zo("key",t.key,r,i);if(a===nr)return nr;a===bi&&(t.key=null);let o=await zo("value",t.value,r,i);if(o===nr)return nr;o===bi&&(t.value=null)}}return n}function tb(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function rb(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(st.isMap(t))return r.Map?.(e,t,i);if(st.isSeq(t))return r.Seq?.(e,t,i);if(st.isPair(t))return r.Pair?.(e,t,i);if(st.isScalar(t))return r.Scalar?.(e,t,i);if(st.isAlias(t))return r.Alias?.(e,t,i)}function ib(e,t,r){let i=t[t.length-1];if(st.isCollection(i))i.items[e]=r;else if(st.isPair(i))e==="key"?i.key=r:i.value=r;else if(st.isDocument(i))i.contents=r;else{let n=st.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Kp.visit=sd;Kp.visitAsync=cd});var Yp=x(ab=>{"use strict";var nb=le(),Hj=kc(),Dj={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bj=e=>e.replace(/[!,[\]{}]/g,t=>Dj[t]),Sc=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Bj(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&nb.isNode(t.contents)){let a={};Hj.visit(t.contents,(o,s)=>{nb.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
6
|
+
`)}};Sc.defaultYaml={explicit:!1,version:"1.2"};Sc.defaultTags={"!!":"tag:yaml.org,2002:"};ab.Directives=Sc});var ld=x(Ec=>{"use strict";var ob=le(),qj=kc();function Fj(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function sb(e){let t=new Set;return qj.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function cb(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Mj(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=sb(e));let o=cb(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(ob.isScalar(o.node)||ob.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Ec.anchorIsValid=Fj;Ec.anchorNames=sb;Ec.createNodeAnchors=Mj;Ec.findNewAnchor=cb});var Xp=x(lb=>{"use strict";function Rc(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Rc(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Rc(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Rc(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Rc(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}lb.applyReviver=Rc});var In=x(db=>{"use strict";var Lj=le();function ub(e,t,r){if(Array.isArray(e))return e.map((i,n)=>ub(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!Lj.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}db.toJS=ub});var ud=x(hb=>{"use strict";var Vj=Xp(),fb=le(),Wj=In(),Qp=class{constructor(t){Object.defineProperty(this,fb.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!fb.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Wj.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Vj.applyReviver(a,{"":s},"",s):s}};hb.NodeBase=Qp});var Pc=x(pb=>{"use strict";var zj=ld(),Jj=kc(),Jo=le(),Gj=ud(),Uj=In(),Zp=class extends Gj.NodeBase{constructor(t){super(Jo.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Jj.visit(t,{Node:(a,o)=>{(Jo.isAlias(o)||Jo.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Uj.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=dd(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(zj.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function dd(e,t,r){if(Jo.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Jo.isCollection(t)){let i=0;for(let n of t.items){let a=dd(e,n,r);a>i&&(i=a)}return i}else if(Jo.isPair(t)){let i=dd(e,t.key,r),n=dd(e,t.value,r);return Math.max(i,n)}return 1}pb.Alias=Zp});var et=x(em=>{"use strict";var Kj=le(),Yj=ud(),Xj=In(),Qj=e=>!e||typeof e!="function"&&typeof e!="object",Tn=class extends Yj.NodeBase{constructor(t){super(Kj.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Xj.toJS(this.value,t,r)}toString(){return String(this.value)}};Tn.BLOCK_FOLDED="BLOCK_FOLDED";Tn.BLOCK_LITERAL="BLOCK_LITERAL";Tn.PLAIN="PLAIN";Tn.QUOTE_DOUBLE="QUOTE_DOUBLE";Tn.QUOTE_SINGLE="QUOTE_SINGLE";em.Scalar=Tn;em.isScalarValue=Qj});var Cc=x(vb=>{"use strict";var Zj=Pc(),Da=le(),mb=et(),e$="tag:yaml.org,2002:";function t$(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function r$(e,t,r){if(Da.isDocument(e)&&(e=e.contents),Da.isNode(e))return e;if(Da.isPair(e)){let d=r.schema[Da.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Zj.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=e$+t.slice(2));let l=t$(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new mb.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Da.MAP]:Symbol.iterator in Object(e)?o[Da.SEQ]:o[Da.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new mb.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}vb.createNode=r$});var hd=x(fd=>{"use strict";var i$=Cc(),ki=le(),n$=ud();function tm(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return i$.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var gb=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,rm=class extends n$.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>ki.isNode(i)||ki.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(gb(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(ki.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,tm(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(ki.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&ki.isScalar(a)?a.value:a:ki.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!ki.isPair(r))return!1;let i=r.value;return i==null||t&&ki.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return ki.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(ki.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,tm(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};fd.Collection=rm;fd.collectionFromPath=tm;fd.isEmptyPath=gb});var xc=x(pd=>{"use strict";var a$=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function im(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var o$=(e,t,r)=>e.endsWith(`
|
|
7
7
|
`)?im(r,t):r.includes(`
|
|
8
8
|
`)?`
|
|
9
9
|
`+im(r,t):(e.endsWith(" ")?"":" ")+r;pd.indentComment=im;pd.lineComment=o$;pd.stringifyComment=a$});var yb=x(Ac=>{"use strict";var s$="flow",nm="block",md="quoted";function c$(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let f,p,v=!1,h=-1,m=-1,g=-1;r===nm&&(h=wb(e,h,t.length),h!==-1&&(d=h+c));for(let S;S=e[h+=1];){if(r===md&&S==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(S===`
|
|
@@ -12,7 +12,7 @@ var oj=Object.create;var Vp=Object.defineProperty;var sj=Object.getOwnPropertyDe
|
|
|
12
12
|
`&&N!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===md){for(;p===" "||p===" ";)p=S,S=e[h+=1],v=!0;let N=h>g+1?h-2:m-1;if(u[N])return e;l.push(N),u[N]=!0,d=N+c,f=void 0}else v=!0}p=S}if(v&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let S=0;S<l.length;++S){let N=l[S],y=l[S+1]||e.length;N===0?w=`
|
|
13
13
|
${t}${e.slice(0,y)}`:(r===md&&u[N]&&(w+=`${e[N]}\\`),w+=`
|
|
14
14
|
${t}${e.slice(N+1,y)}`)}return w}function wb(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
15
|
-
`);i=t,n=t+1,a=e[n]}return i}Ac.FOLD_BLOCK=nm;Ac.FOLD_FLOW=s$;Ac.FOLD_QUOTED=md;Ac.foldFlowLines=c$});var Ic=x(Nb=>{"use strict";var
|
|
15
|
+
`);i=t,n=t+1,a=e[n]}return i}Ac.FOLD_BLOCK=nm;Ac.FOLD_FLOW=s$;Ac.FOLD_QUOTED=md;Ac.foldFlowLines=c$});var Ic=x(Nb=>{"use strict";var ei=et(),jn=yb(),gd=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),wd=e=>/^(%|---|\.\.\.)/m.test(e);function l$(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
16
16
|
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function _c(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(wd(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
17
17
|
|
|
18
18
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
@@ -21,28 +21,28 @@ ${t}${e.slice(N+1,y)}`)}return w}function wb(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
|
|
|
21
21
|
${r}`)+"'";return t.implicitKey?i:jn.foldFlowLines(i,r,jn.FOLD_FLOW,gd(t,!1))}function Go(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=_c;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=am:a&&!n?i=_c:i=r?am:_c}return i(e,t)}var om;try{om=new RegExp(`(^|(?<!
|
|
22
22
|
))
|
|
23
23
|
+(?!
|
|
24
|
-
|$)`,"g")}catch{om=/\n+(?!\n|$)/g}function vd({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Go(r,i);let l=i.indent||(i.forceBlockIndent||wd(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===
|
|
24
|
+
|$)`,"g")}catch{om=/\n+(?!\n|$)/g}function vd({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Go(r,i);let l=i.indent||(i.forceBlockIndent||wd(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===ei.Scalar.BLOCK_FOLDED?!1:t===ei.Scalar.BLOCK_LITERAL?!0:!l$(r,c,l.length);if(!r)return u?`|
|
|
25
25
|
`:`>
|
|
26
26
|
`;let d,f;for(f=r.length;f>0;--f){let y=r[f-1];if(y!==`
|
|
27
27
|
`&&y!==" "&&y!==" ")break}let p=r.substring(f),v=p.indexOf(`
|
|
28
28
|
`);v===-1?d="-":r===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
29
29
|
`&&(p=p.slice(0,-1)),p=p.replace(om,`$&${l}`));let h=!1,m,g=-1;for(m=0;m<r.length;++m){let y=r[m];if(y===" ")h=!0;else if(y===`
|
|
30
30
|
`)g=m;else break}let w=r.substring(0,g<m?g+1:m);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let N=(h?l?"2":"1":"")+d;if(e&&(N+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let y=r.replace(/\n+/g,`
|
|
31
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,P=gd(i,!0);o!=="folded"&&t!==
|
|
31
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,P=gd(i,!0);o!=="folded"&&t!==ei.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{E=!0});let b=jn.foldFlowLines(`${w}${y}${p}`,l,jn.FOLD_BLOCK,P);if(!E)return`>${N}
|
|
32
32
|
${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${N}
|
|
33
33
|
${l}${w}${r}${p}`}function u$(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
34
34
|
`)||u&&/[[\]{},]/.test(a))return Go(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
35
|
-
`)?Go(a,t):vd(e,t,r,i);if(!s&&!u&&n!==
|
|
35
|
+
`)?Go(a,t):vd(e,t,r,i);if(!s&&!u&&n!==ei.Scalar.PLAIN&&a.includes(`
|
|
36
36
|
`))return vd(e,t,r,i);if(wd(a)){if(c==="")return t.forceBlockIndent=!0,vd(e,t,r,i);if(s&&c===l)return Go(a,t)}let d=a.replace(/\n+/g,`$&
|
|
37
|
-
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Go(a,t)}return s?d:jn.foldFlowLines(d,c,jn.FOLD_FLOW,gd(t,!1))}function d$(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==
|
|
38
|
-
${t.indent}${s}`:s}sm.createStringifyContext=m$;sm.stringify=w$});var Eb=x(Sb=>{"use strict";var
|
|
39
|
-
${s}:`):(m=`${m}:`,f&&(m+=jc.lineComment(m,r.indent,l(f))));let g,w,S;
|
|
37
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(f)||p?.some(f))return Go(a,t)}return s?d:jn.foldFlowLines(d,c,jn.FOLD_FLOW,gd(t,!1))}function d$(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==ei.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ei.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case ei.Scalar.BLOCK_FOLDED:case ei.Scalar.BLOCK_LITERAL:return n||a?Go(o.value,t):vd(o,t,r,i);case ei.Scalar.QUOTE_DOUBLE:return _c(o.value,t);case ei.Scalar.QUOTE_SINGLE:return am(o.value,t);case ei.Scalar.PLAIN:return u$(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Nb.stringifyString=d$});var Tc=x(sm=>{"use strict";var f$=ld(),$n=le(),h$=xc(),p$=Ic();function m$(e,t){let r=Object.assign({blockQuote:!0,commentString:h$.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function v$(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if($n.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function g$(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=($n.isScalar(e)||$n.isCollection(e))&&e.anchor;a&&f$.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function w$(e,t,r,i){if($n.isPair(e))return e.toString(t,r,i);if($n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=$n.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=v$(t.doc.schema.tags,a));let o=g$(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):$n.isScalar(a)?p$.stringifyString(a,t,r,i):a.toString(t,r,i);return o?$n.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
38
|
+
${t.indent}${s}`:s}sm.createStringifyContext=m$;sm.stringify=w$});var Eb=x(Sb=>{"use strict";var Ji=le(),bb=et(),kb=Tc(),jc=xc();function y$({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=Ji.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ji.isCollection(e)||!Ji.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||Ji.isCollection(e)||(Ji.isScalar(e)?e.type===bb.Scalar.BLOCK_FOLDED||e.type===bb.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,h=!1,m=kb.stringify(e,r,()=>v=!0,()=>h=!0);if(!p&&!r.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,f&&!v?m+=jc.lineComment(m,r.indent,l(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=jc.lineComment(m,r.indent,l(f))),m=`? ${m}
|
|
39
|
+
${s}:`):(m=`${m}:`,f&&(m+=jc.lineComment(m,r.indent,l(f))));let g,w,S;Ji.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,S=t.comment):(g=!1,w=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&Ji.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&Ji.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let N=!1,y=kb.stringify(t,r,()=>N=!0,()=>h=!0),E=" ";if(f||g||w){if(E=g?`
|
|
40
40
|
`:"",w){let P=l(w);E+=`
|
|
41
41
|
${jc.indentComment(P,r.indent)}`}y===""&&!r.inFlow?E===`
|
|
42
42
|
`&&S&&(E=`
|
|
43
43
|
|
|
44
44
|
`):E+=`
|
|
45
|
-
${r.indent}`}else if(!p&&
|
|
45
|
+
${r.indent}`}else if(!p&&Ji.isCollection(t)){let P=y[0],b=y.indexOf(`
|
|
46
46
|
`),k=b!==-1,R=r.inFlow??t.flow??t.items.length===0;if(k||!R){let I=!1;if(k&&(P==="&"||P==="!")){let C=y.indexOf(" ");P==="&"&&C!==-1&&C<b&&y[C+1]==="!"&&(C=y.indexOf(" ",C+1)),(C===-1||b<C)&&(I=!0)}I||(E=`
|
|
47
47
|
${r.indent}`)}}else(y===""||y[0]===`
|
|
48
48
|
`)&&(E="");return m+=E+y,r.inFlow?N&&i&&i():S&&!N?m+=jc.lineComment(m,r.indent,l(S)):h&&n&&n(),m}Sb.stringifyPair=y$});var lm=x(cm=>{"use strict";var Rb=Zu("process");function N$(e,...t){e==="debug"&&console.log(...t)}function b$(e,t){(e==="debug"||e==="warn")&&(typeof Rb.emitWarning=="function"?Rb.emitWarning(t):console.warn(t))}cm.debug=N$;cm.warn=b$});var Sd=x(kd=>{"use strict";var bd=le(),Pb=et(),yd="<<",Nd={identify:e=>e===yd||typeof e=="symbol"&&e.description===yd,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Pb.Scalar(Symbol(yd)),{addToJSMap:Cb}),stringify:()=>yd},k$=(e,t)=>(Nd.identify(t)||bd.isScalar(t)&&(!t.type||t.type===Pb.Scalar.PLAIN)&&Nd.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Nd.tag&&r.default);function Cb(e,t,r){let i=xb(e,r);if(bd.isSeq(i))for(let n of i.items)um(e,t,n);else if(Array.isArray(i))for(let n of i)um(e,t,n);else um(e,t,i)}function um(e,t,r){let i=xb(e,r);if(!bd.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function xb(e,t){return e&&bd.isAlias(t)?t.resolve(e.doc,e):t}kd.addMergeToJSMap=Cb;kd.isMergeKey=k$;kd.merge=Nd});var fm=x(Ib=>{"use strict";var S$=lm(),Ab=Sd(),E$=Tc(),_b=le(),dm=In();function R$(e,t,{key:r,value:i}){if(_b.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Ab.isMergeKey(e,r))Ab.addMergeToJSMap(e,t,i);else{let n=dm.toJS(r,"",e);if(t instanceof Map)t.set(n,dm.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=P$(r,n,e),o=dm.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function P$(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(_b.isNode(e)&&r?.doc){let i=E$.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),S$.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Ib.addPairToJSMap=R$});var On=x(hm=>{"use strict";var Tb=Cc(),C$=Eb(),x$=fm(),Ed=le();function A$(e,t,r){let i=Tb.createNode(e,void 0,r),n=Tb.createNode(t,void 0,r);return new Rd(i,n)}var Rd=class e{constructor(t,r=null){Object.defineProperty(this,Ed.NODE_TYPE,{value:Ed.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return Ed.isNode(r)&&(r=r.clone(t)),Ed.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return x$.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?C$.stringifyPair(this,t,r,i):JSON.stringify(this)}};hm.Pair=Rd;hm.createPair=A$});var pm=x($b=>{"use strict";var Ba=le(),jb=Tc(),Pd=xc();function _$(e,t,r){return(t.inFlow??e.flow?T$:I$)(e,t,r)}function I$({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(Ba.isNode(h))!d&&h.spaceBefore&&f.push(""),Cd(r,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(Ba.isPair(h)){let w=Ba.isNode(h.key)?h.key:null;w&&(!d&&w.spaceBefore&&f.push(""),Cd(r,f,w.commentBefore,d))}d=!1;let g=jb.stringify(h,u,()=>m=null,()=>d=!0);m&&(g+=Pd.lineComment(g,a,l(m))),d&&m&&(d=!1),f.push(i+g)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
|
|
@@ -117,24 +117,24 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
117
117
|
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function vS(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function fv(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
118
118
|
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Kd.createScalarToken=kH;Kd.resolveAsScalar=bH;Kd.setScalarValue=SH});var yS=x(wS=>{"use strict";var RH=e=>"type"in e?Xd(e):Yd(e);function Xd(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Xd(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Yd(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Yd(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Yd(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Yd({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Xd(t)),r)for(let a of r)n+=a.source;return i&&(n+=Xd(i)),n}wS.stringify=RH});var SS=x(kS=>{"use strict";var hv=Symbol("break visit"),PH=Symbol("skip children"),NS=Symbol("remove item");function La(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),bS(Object.freeze([]),e,t)}La.BREAK=hv;La.SKIP=PH;La.REMOVE=NS;La.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};La.parentCollection=(e,t)=>{let r=La.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function bS(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=bS(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===hv)return hv;s===NS&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}kS.visit=La});var Qd=x(ar=>{"use strict";var pv=gS(),CH=yS(),xH=SS(),mv="\uFEFF",vv="",gv="",wv="",AH=e=>!!e&&"items"in e,_H=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function IH(e){switch(e){case mv:return"<BOM>";case vv:return"<DOC>";case gv:return"<FLOW_END>";case wv:return"<SCALAR>";default:return JSON.stringify(e)}}function TH(e){switch(e){case mv:return"byte-order-mark";case vv:return"doc-mode";case gv:return"flow-error-end";case wv:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
119
119
|
`:case`\r
|
|
120
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ar.createScalarToken=pv.createScalarToken;ar.resolveAsScalar=pv.resolveAsScalar;ar.setScalarValue=pv.setScalarValue;ar.stringify=CH.stringify;ar.visit=xH.visit;ar.BOM=mv;ar.DOCUMENT=vv;ar.FLOW_END=gv;ar.SCALAR=wv;ar.isCollection=AH;ar.isScalar=_H;ar.prettyToken=IH;ar.tokenType=TH});var bv=x(RS=>{"use strict";var Kc=Qd();function
|
|
120
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ar.createScalarToken=pv.createScalarToken;ar.resolveAsScalar=pv.resolveAsScalar;ar.setScalarValue=pv.setScalarValue;ar.stringify=CH.stringify;ar.visit=xH.visit;ar.BOM=mv;ar.DOCUMENT=vv;ar.FLOW_END=gv;ar.SCALAR=wv;ar.isCollection=AH;ar.isScalar=_H;ar.prettyToken=IH;ar.tokenType=TH});var bv=x(RS=>{"use strict";var Kc=Qd();function ti(e){switch(e){case void 0:case" ":case`
|
|
121
121
|
`:case"\r":case" ":return!0;default:return!1}}var ES=new Set("0123456789ABCDEFabcdef"),jH=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Zd=new Set(",[]{}"),$H=new Set(` ,[]{}
|
|
122
122
|
\r `),yv=e=>!e||$H.has(e),Nv=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
123
123
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
124
124
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
125
125
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
126
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
127
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Kc.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Kc.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&
|
|
126
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&ti(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
127
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Kc.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Kc.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ti(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ti(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ti(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(yv),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&ti(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Kc.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(yv),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ti(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
128
128
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
129
|
-
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>
|
|
129
|
+
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>ti(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
130
130
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
131
131
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
132
132
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
133
133
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
134
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Kc.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(
|
|
134
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Kc.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(ti(a)||t&&Zd.has(a))break;r=i}else if(ti(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
135
135
|
`?(i+=1,n=`
|
|
136
136
|
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Zd.has(a))break;if(n===`
|
|
137
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Zd.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Kc.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(yv),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(
|
|
137
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Zd.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Kc.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(yv),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ti(i)||r&&Zd.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!ti(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(jH.has(r))r=this.buffer[++t];else if(r==="%"&&ES.has(this.buffer[t+1])&&ES.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
138
138
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
139
139
|
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};RS.Lexer=Nv});var Sv=x(PS=>{"use strict";var kv=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};PS.LineCounter=kv});var Rv=x(IS=>{"use strict";var OH=Zu("process"),CS=Qd(),HH=bv();function qn(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function xS(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function _S(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function ef(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function es(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function tf(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function AS(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!qn(t.start,"explicit-key-ind")&&!qn(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,_S(t.value)?t.value.end?tf(t.value.end,t.sep):t.value.end=t.sep:tf(t.start,t.sep),delete t.sep)}var Ev=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new HH.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,OH.env.LOG_TOKENS&&console.log("|",CS.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=CS.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&AS(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&xS(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{xS(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=ef(this.peek(2)),i=es(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
140
140
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
@@ -145,7 +145,7 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
145
145
|
`)}function or(e,t,r){return e==="zh-CN"?r:t}var Cv,BS,qS,FS,xv,Va=_(()=>{"use strict";Cv={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},BS={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},qS={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},FS=new Map,xv=new Map;for(let e of Object.keys(Cv)){for(let[t,r]of Object.entries(Cv[e]))FS.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(BS[e]))xv.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(qS[e]))xv.set(r.toLocaleLowerCase("en-US"),t)}});import Ln from"path";function GS(e){let t=[...e],r=new Set(e);for(let i of JS)r.has(i)||(r.add(i),t.push(i));return t}function US(e,t){return ts[t][e]}function oD(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in ts.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in ts.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in ts.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in ts.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in ts.en)return s}return null}function rl(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,el.stringify)(e).trimEnd().split(`
|
|
146
146
|
`)){let s=oD(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of US(s,t).split(`
|
|
147
147
|
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
148
|
-
`)}function sD(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ln.posix.isAbsolute(r)||Ln.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Wa(e){let t=sD(e,"native.artifact_root");return t.length===0?".":t.join("/")}function KS(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function sf(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ln.posix.isAbsolute(i)||Ln.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ji(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function YS(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function cf(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>af)throw new Error(`${t} exceeds ${af} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>of)throw new Error(`${t} contains more than ${of} wildcard tokens`);return e}function zS(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>cf(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function _v(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function cD(e){if(e===void 0)return{...sr,include:[...sr.include],exclude:[...sr.exclude]};let t=Ji(e,"native.snapshot");return{include:zS(t.include,"native.snapshot.include",sr.include),exclude:zS(t.exclude,"native.snapshot.exclude",sr.exclude),max_files:_v(t.max_files,sr.max_files,"native.snapshot.max_files"),max_total_bytes:_v(t.max_total_bytes,sr.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:_v(t.max_duration_ms,sr.max_duration_ms,"native.snapshot.max_duration_ms")}}function lD(e){if(e===void 0)return;let t=Ji(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Ji(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Wa(i),toArtifactRoot:Wa(n),stage:a,...o?{cleanup:o}:{}}}function uD(e){if(e===void 0)return;let t=Ji(e,"native.finish");if(t.pull_request===void 0)return{};let r=Ji(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ln.posix.isAbsolute(i[0])||Ln.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??iD;if(!Number.isSafeInteger(n)||n<1||n>WS)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${WS}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function dD(e,t={}){let r=Ji(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Iv;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=lD(r.pending_root_move),c=uD(r.finish);return{artifact_root:Wa(i),language:YS(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:cD(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function fD(e){let t=Ji(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:KS(t.artifact_layout),language:YS(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function hD(e){let r=Ji(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>sf(i,`hook.allow_paths[${n}]`)))]}}function pD(e){if(e===void 0)return{...Zc};let t=Ji(e,"memory"),r=t.learning??Zc.learning,i=t.retrieval??Zc.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function jv(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mD(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ln.posix.isAbsolute(r)||Ln.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>LS)throw new Error(`${t} exceeds ${LS} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>VS)throw new Error(`${t} contains more than ${VS} wildcard tokens`);return r}function vD(e){let r=jv(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>mD(i,`knowledge.local.include[${n}]`)))]}}function gD(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function wD(e){let t=jv(e,"knowledge.remote"),r=gD(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function yD(e){if(e===void 0)return{...Tv};let t=jv(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:vD(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:wD(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function ND(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function bD(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function rs(e,t={}){let r=(0,el.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=ND(n.ambient_resume),o=n.hook===void 0?void 0:hD(n.hook),s=pD(n.memory),c=yD(n.knowledge),l=n.native===void 0?void 0:dD(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:fD(n.classic),d=bD(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function XS(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function QS(e){let t=e.knowledge??{...Tv};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Zc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:XS(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function yr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function il(e,t){let r=QS(t),i=rs((0,el.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...yr(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=yr(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=yr(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...yr(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...yr(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=yr(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=yr(a.finish);o.finish={...s,pull_request:{...yr(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...yr(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=yr(a.pending_root_move),c=XS(i.native.pending_root_move),l=yr(s.cleanup),u=yr(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...yr(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function lf(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Zc},knowledge:{...Tv},native:{artifact_root:Wa(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Iv,snapshot:{...sr,include:[...sr.include],exclude:[...sr.exclude]}}}}var el,tl,af,of,LS,VS,Iv,Zc,Tv,iD,WS,nD,aD,JS,sr,ts,Vn=_(()=>{"use strict";el=Ha(Mn(),1),tl=64*1024,af=1024,of=64,LS=1024,VS=64,Iv=5,Zc={learning:!0,retrieval:!0},Tv={provider:"local"},iD=12e4,WS=6e5,nD=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],aD=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],JS=[...nD,...aD].sort((e,t)=>e.localeCompare(t,"en"));sr={include:["**/*"],exclude:[...JS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},ts={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
148
|
+
`)}function sD(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ln.posix.isAbsolute(r)||Ln.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Wa(e){let t=sD(e,"native.artifact_root");return t.length===0?".":t.join("/")}function KS(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function sf(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ln.posix.isAbsolute(i)||Ln.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function YS(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function cf(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>af)throw new Error(`${t} exceeds ${af} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>of)throw new Error(`${t} contains more than ${of} wildcard tokens`);return e}function zS(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>cf(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function _v(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function cD(e){if(e===void 0)return{...sr,include:[...sr.include],exclude:[...sr.exclude]};let t=Gi(e,"native.snapshot");return{include:zS(t.include,"native.snapshot.include",sr.include),exclude:zS(t.exclude,"native.snapshot.exclude",sr.exclude),max_files:_v(t.max_files,sr.max_files,"native.snapshot.max_files"),max_total_bytes:_v(t.max_total_bytes,sr.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:_v(t.max_duration_ms,sr.max_duration_ms,"native.snapshot.max_duration_ms")}}function lD(e){if(e===void 0)return;let t=Gi(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Gi(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Wa(i),toArtifactRoot:Wa(n),stage:a,...o?{cleanup:o}:{}}}function uD(e){if(e===void 0)return;let t=Gi(e,"native.finish");if(t.pull_request===void 0)return{};let r=Gi(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ln.posix.isAbsolute(i[0])||Ln.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??iD;if(!Number.isSafeInteger(n)||n<1||n>WS)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${WS}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function dD(e,t={}){let r=Gi(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Iv;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=lD(r.pending_root_move),c=uD(r.finish);return{artifact_root:Wa(i),language:YS(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:cD(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function fD(e){let t=Gi(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:KS(t.artifact_layout),language:YS(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function hD(e){let r=Gi(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>sf(i,`hook.allow_paths[${n}]`)))]}}function pD(e){if(e===void 0)return{...Zc};let t=Gi(e,"memory"),r=t.learning??Zc.learning,i=t.retrieval??Zc.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function jv(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mD(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ln.posix.isAbsolute(r)||Ln.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>LS)throw new Error(`${t} exceeds ${LS} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>VS)throw new Error(`${t} contains more than ${VS} wildcard tokens`);return r}function vD(e){let r=jv(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>mD(i,`knowledge.local.include[${n}]`)))]}}function gD(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function wD(e){let t=jv(e,"knowledge.remote"),r=gD(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function yD(e){if(e===void 0)return{...Tv};let t=jv(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:vD(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:wD(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function ND(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function bD(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function rs(e,t={}){let r=(0,el.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=ND(n.ambient_resume),o=n.hook===void 0?void 0:hD(n.hook),s=pD(n.memory),c=yD(n.knowledge),l=n.native===void 0?void 0:dD(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:fD(n.classic),d=bD(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function XS(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function QS(e){let t=e.knowledge??{...Tv};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Zc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:XS(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function yr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function il(e,t){let r=QS(t),i=rs((0,el.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...yr(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=yr(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=yr(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...yr(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...yr(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=yr(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=yr(a.finish);o.finish={...s,pull_request:{...yr(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...yr(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=yr(a.pending_root_move),c=XS(i.native.pending_root_move),l=yr(s.cleanup),u=yr(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...yr(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function lf(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Zc},knowledge:{...Tv},native:{artifact_root:Wa(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Iv,snapshot:{...sr,include:[...sr.include],exclude:[...sr.exclude]}}}}var el,tl,af,of,LS,VS,Iv,Zc,Tv,iD,WS,nD,aD,JS,sr,ts,Vn=_(()=>{"use strict";el=Ha(Mn(),1),tl=64*1024,af=1024,of=64,LS=1024,VS=64,Iv=5,Zc={learning:!0,retrieval:!0},Tv={provider:"local"},iD=12e4,WS=6e5,nD=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],aD=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],JS=[...nD,...aD].sort((e,t)=>e.localeCompare(t,"en"));sr={include:["**/*"],exclude:[...JS],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},ts={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
149
149
|
# ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
150
150
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
151
151
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -169,52 +169,52 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
169
169
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
170
170
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
171
171
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
172
|
-
# 可选值:true | false`}}});import{constants as uf,promises as za}from"fs";function $v(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ZS(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nl(e){return{dev:e.dev,ino:e.ino,birthtime:$v(e)}}function df(e,t){let r=nl(e),i=nl(t);return wr(r,i)?J(r,i):J(r,i)&&$v(e)===$v(t)&&ZS(e)===ZS(t)&&e.size===t.size}async function Ja(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await za.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ti("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ti("too-large",`${i} exceeds ${t} bytes`);let o=await za.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:nl(a)});let s=process.platform==="win32"?uf.O_RDONLY:uf.O_RDONLY|uf.O_NOFOLLOW|uf.O_NONBLOCK,c;try{c=await za.open(e,s)}catch(l){throw l.code==="ELOOP"?new ti("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),za.lstat(e,{bigint:n}),za.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!df(a,l)||!df(a,u))throw new ti("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:nl(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:S}=await c.read(v,0,Math.min(v.length,w),null);if(S===0)break;if(p+=S,p>t)throw new ti("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),za.lstat(e,{bigint:n}),za.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!df(a,h)||!df(a,m))throw new ti("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:nl(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var ti,al=_(()=>{"use strict";yc();ti=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as ff}from"fs";import Wn from"path";function kD(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ov(e,t){let r=Wn.relative(e,t);return r===""||!Wn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Wn.sep}`)}async function eE(e,t){let r=Wn.resolve(e),i=await ff.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ff.realpath(r)}async function tE(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Wn.join(n,r[a]);let o;try{o=await ff.lstat(n)}catch(u){if(kD(u))return{exists:!1,kind:"missing"};throw u}let s=Wn.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ff.realpath(n);if(!Ov(t,l))throw new Error(`${i.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 Gi(e,t,r){let i=sf(t,r.label),n=Wn.resolve(e),a=await eE(n,r.label),o=i.split("/"),s=Wn.resolve(n,...o);if(!Ov(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await tE(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function ki(e,t,r,i){let n=await Gi(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await eE(n.projectRoot,i.label);return Ja(n.target,r,{...i,verify:async(o,s)=>{if(!Ov(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await tE(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Ga=_(()=>{"use strict";al();Vn()});import{createHash as SD}from"crypto";function Hv(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function ED(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function hf(e,t={}){return(await sl(e,t)).document}async function rE(e){try{return(await ki(e,ol,tl,{label:ol})).bytes}catch(t){if(ED(t))return null;throw t}}function iE(e){return e?{exists:!0,sha256:SD("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function pf(e){return iE(await rE(e))}async function sl(e,t={}){let r=await rE(e);return{document:r?rs(r.toString("utf8"),t):null,identity:iE(r)}}async function Dv(e){return(await hf(e))?.config??null}var ol,is=_(()=>{"use strict";Vn();Ga();ol=".comet/config.yaml"});import{randomUUID as RD}from"crypto";import{constants as PD,promises as Et}from"fs";import ri from"path";async function Bv(e,t){try{return await Et.link(e,t),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await Et.copyFile(e,t,PD.COPYFILE_EXCL),{linked:!1}}function mf(e,t){let r=ri.relative(e,t);return r===""||!ri.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ri.sep}`)}function vf(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function CD(e,t){return J(e,vf(t))}function gf(e,t){return J(vf(e),vf(t))}function xD(e,t){return gf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nE(e){let t=await Et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),...vf(t)}}async function ns(e){for(let t of e){let r=await Et.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!CD(t,r)||await Et.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function AD(e,t,r){let[i,n]=await Promise.all([Et.lstat(e),Et.realpath(e),ns(r)]);if(!i.isFile()||i.isSymbolicLink()||!gf(i,t)||!mf(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function _D(e,t){let r=ri.resolve(e),i=ri.resolve(t);if(!mf(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await nE(r)],a=ri.relative(r,i).split(ri.sep).filter(Boolean),o=r;for(let s of a){await ns(n),o=ri.join(o,s);try{await Et.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await nE(o);if(!mf(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ns(n),n}async function ID(e){let t;try{t=await Et.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function TD(e,t,r){let i=ri.dirname(e),n=await _D(r.containedRoot,i),a=ri.join(i,`.${ri.basename(e)}.${RD()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await Et.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([Et.lstat(a),Et.realpath(a)]);if(await ns(n),!l.isFile()||l.isSymbolicLink()||!gf(s,l)||!mf(n[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!gf(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await AD(a,c,n),await r.beforeCommit?.(),await ns(n);let d=await Et.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!xD(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Bv(a,e),await Et.unlink(a)):await Et.rename(a,e),await ID(i)}catch(l){await o?.close();try{await ns(n),await Et.rm(a,{force:!0})}catch{}throw l}}async function Ua(e,t,r){await TD(e,t,r)}var as=_(()=>{"use strict";yc()});var qY,qv=_(()=>{"use strict";as();is();Ga();qY=16*1024});async function Fv(e,t){if(!t)return;let r=await pf(e);if(!Hv(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Mv=_(()=>{"use strict";as();Vn();is();Ga();qv()});import{existsSync as aE,promises as Si}from"fs";import he from"path";import OD from"os";async function Lv(e){try{return await Si.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function DD(e){try{let t=await Si.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ss(e,t){let r=he.relative(e,t);return r===""||!he.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${he.sep}`)}async function os(e){let t=[],r=e;for(;!await Lv(r);){let n=he.dirname(r);if(n===r)break;t.push(he.basename(r)),r=n}let i=await Si.realpath(r);return he.resolve(i,...t.reverse())}async function Vv(e){try{return(await Si.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wf(e){let t=he.resolve(e);try{(await Si.stat(t)).isDirectory()||(t=he.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=he.resolve(OD.homedir());for(;;){if(!(t===i&&r!==i)){let o=he.join(t,...cl.split("/")),s=t===r||await DD(o);if(await Lv(o)&&s)return t}if(await Lv(he.join(t,".git")))return t;let a=he.dirname(t);if(a===t)return r;t=a}}function zn(e){return Wa(e)}async function BD(e,t){let r=zn(t),i=he.resolve(e,...r.split("/")),n=await Si.realpath(e),a=await os(i);if(!ss(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function pe(e,t){let r=zn(t),i=await BD(e,r),n=he.join(i,"comet");if(await Vv(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([os(i),os(n)]);if(!ss(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=he.resolve(e),c=he.join(s,".comet","runtime","native");if(await Vv(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Si.realpath(s),os(c)]);if(!ss(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:he.join(e,...cl.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:he.join(n,"specs"),changesDir:he.join(n,"changes"),archiveDir:he.join(n,"archive"),runtimeDir:c,changesRuntimeDir:he.join(c,"changes"),locksDir:he.join(c,"locks"),transactionsDir:he.join(c,"transactions")}}async function yf(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await j(e.nativeRoot,t),await Si.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await j(e.projectRoot,t),await Si.mkdir(t,{recursive:!0})}))}function sE(e){if(!HD.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Oe(e,t){sE(t);let r=he.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ka(e,t){sE(t);let r=he.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function V(e,t){let r=Oe(e,t);if(aE(r))return r;let i=Ka(e,t);return aE(i)?i:r}async function oE(e){try{let t=await Si.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function ll(e,t){let r=Oe(e,t),i=Ka(e,t),[n,a]=await Promise.all([oE(r),oE(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Jn(e,t){if(!t.startsWith("runtime/")||he.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=he.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function F(e,t){let r=he.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return ss(he.resolve(e),he.resolve(t))}async function j(e,t){let r=he.resolve(e),i=he.resolve(t);if(!ss(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Vv(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([os(r),os(i)]);if(!ss(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var cl,HD,Q=_(()=>{"use strict";Vn();cl=".comet/config.yaml",HD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import qD from"path";function Ya(e="docs",t="en"){return lf(e,t)}async function X(e){let t=(await hf(e))?.config??null;return t?.native?t:null}async function cs(e){let t=await X(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Nr(e,t,r={}){let i=await sl(e,{allowPartialProject:!0}),n=il(i.document?.value??{},t),a=qD.join(e,...cl.split("/"));await xe(a,rl(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Fv(e,i.identity)}})}async function lE(e){let t=await wf(e.startPath),r=await X(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${cl} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?zn(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Ya(i??"docs"),a=await pe(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Wv,Nf,cE,tt=_(()=>{"use strict";Vn();is();Mv();$e();Q();Wv=sr,Nf=cf,cE=GS});import{AsyncLocalStorage as FD}from"async_hooks";import{randomUUID as fE}from"crypto";import{promises as $r}from"fs";import hE from"os";import Me from"path";function LD(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function VD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function pE(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function kf(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return wr(r,i)?J(r,i):J(r,i)&&e.size===t.size}function Sf(e,t){return kf(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function WD(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Sf(e.identity,t.identity)}async function ii(e){let t,r;try{let i=await Ja(e,uE,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof ti?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${uE} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:VD(JSON.parse(t.toString("utf8")),e),identity:pE(r)}}async function zD(e){return(await ii(e))?.owner??null}function Jv(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==hE.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=XD(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function JD(e,t){try{await $r.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await $r.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ef(e,t){let r=await ii(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Sf(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await $r.mkdir(t,{recursive:!0});let i=Me.join(t,`${Me.basename(e.file)}.${e.owner.id}.${fE()}.removed`);try{await $r.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ii(i);if(!n||n.owner.id!==e.owner.id||!kf(n.identity,e.identity))throw await JD(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await $r.rm(i,{force:!0}),"removed"}function mE(e){return{id:fE(),pid:process.pid,hostname:hE.hostname(),createdAt:new Date().toISOString(),operation:e}}async function vE(e,t){let r;try{r=await $r.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await zD(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
-
`,"utf8"),await r.sync(),i=pE(await r.stat({bigint:!0}))}finally{await r.close()}let n=await
|
|
174
|
-
${dl(t)}`).digest("hex")}var ct=_(()=>{"use strict"});import wE from"node:path";function sB(e,t){return e<t?-1:e>t?1:0}function bE(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function kE(e,t){let r=t.toString(36),i=
|
|
172
|
+
# 可选值:true | false`}}});import{constants as uf,promises as za}from"fs";function $v(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ZS(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nl(e){return{dev:e.dev,ino:e.ino,birthtime:$v(e)}}function df(e,t){let r=nl(e),i=nl(t);return wr(r,i)?J(r,i):J(r,i)&&$v(e)===$v(t)&&ZS(e)===ZS(t)&&e.size===t.size}async function Ja(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await za.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ri("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ri("too-large",`${i} exceeds ${t} bytes`);let o=await za.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:nl(a)});let s=process.platform==="win32"?uf.O_RDONLY:uf.O_RDONLY|uf.O_NOFOLLOW|uf.O_NONBLOCK,c;try{c=await za.open(e,s)}catch(l){throw l.code==="ELOOP"?new ri("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),za.lstat(e,{bigint:n}),za.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!df(a,l)||!df(a,u))throw new ri("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:nl(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:S}=await c.read(v,0,Math.min(v.length,w),null);if(S===0)break;if(p+=S,p>t)throw new ri("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,S)))}await r.hooks?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([c.stat({bigint:n}),za.lstat(e,{bigint:n}),za.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||g!==o||!df(a,h)||!df(a,m))throw new ri("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:nl(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:g}}finally{await c.close()}}var ri,al=_(()=>{"use strict";yc();ri=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as ff}from"fs";import Wn from"path";function kD(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ov(e,t){let r=Wn.relative(e,t);return r===""||!Wn.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Wn.sep}`)}async function eE(e,t){let r=Wn.resolve(e),i=await ff.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ff.realpath(r)}async function tE(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Wn.join(n,r[a]);let o;try{o=await ff.lstat(n)}catch(u){if(kD(u))return{exists:!1,kind:"missing"};throw u}let s=Wn.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ff.realpath(n);if(!Ov(t,l))throw new Error(`${i.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 Ui(e,t,r){let i=sf(t,r.label),n=Wn.resolve(e),a=await eE(n,r.label),o=i.split("/"),s=Wn.resolve(n,...o);if(!Ov(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await tE(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Si(e,t,r,i){let n=await Ui(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await eE(n.projectRoot,i.label);return Ja(n.target,r,{...i,verify:async(o,s)=>{if(!Ov(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await tE(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Ga=_(()=>{"use strict";al();Vn()});import{createHash as SD}from"crypto";function Hv(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function ED(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function hf(e,t={}){return(await sl(e,t)).document}async function rE(e){try{return(await Si(e,ol,tl,{label:ol})).bytes}catch(t){if(ED(t))return null;throw t}}function iE(e){return e?{exists:!0,sha256:SD("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function pf(e){return iE(await rE(e))}async function sl(e,t={}){let r=await rE(e);return{document:r?rs(r.toString("utf8"),t):null,identity:iE(r)}}async function Dv(e){return(await hf(e))?.config??null}var ol,is=_(()=>{"use strict";Vn();Ga();ol=".comet/config.yaml"});import{randomUUID as RD}from"crypto";import{constants as PD,promises as Et}from"fs";import ii from"path";async function Bv(e,t){try{return await Et.link(e,t),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await Et.copyFile(e,t,PD.COPYFILE_EXCL),{linked:!1}}function mf(e,t){let r=ii.relative(e,t);return r===""||!ii.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ii.sep}`)}function vf(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function CD(e,t){return J(e,vf(t))}function gf(e,t){return J(vf(e),vf(t))}function xD(e,t){return gf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nE(e){let t=await Et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),...vf(t)}}async function ns(e){for(let t of e){let r=await Et.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!CD(t,r)||await Et.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function AD(e,t,r){let[i,n]=await Promise.all([Et.lstat(e),Et.realpath(e),ns(r)]);if(!i.isFile()||i.isSymbolicLink()||!gf(i,t)||!mf(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function _D(e,t){let r=ii.resolve(e),i=ii.resolve(t);if(!mf(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await nE(r)],a=ii.relative(r,i).split(ii.sep).filter(Boolean),o=r;for(let s of a){await ns(n),o=ii.join(o,s);try{await Et.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await nE(o);if(!mf(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ns(n),n}async function ID(e){let t;try{t=await Et.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function TD(e,t,r){let i=ii.dirname(e),n=await _D(r.containedRoot,i),a=ii.join(i,`.${ii.basename(e)}.${RD()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await Et.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([Et.lstat(a),Et.realpath(a)]);if(await ns(n),!l.isFile()||l.isSymbolicLink()||!gf(s,l)||!mf(n[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!gf(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await AD(a,c,n),await r.beforeCommit?.(),await ns(n);let d=await Et.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!xD(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Bv(a,e),await Et.unlink(a)):await Et.rename(a,e),await ID(i)}catch(l){await o?.close();try{await ns(n),await Et.rm(a,{force:!0})}catch{}throw l}}async function Ua(e,t,r){await TD(e,t,r)}var as=_(()=>{"use strict";yc()});var qY,qv=_(()=>{"use strict";as();is();Ga();qY=16*1024});async function Fv(e,t){if(!t)return;let r=await pf(e);if(!Hv(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Mv=_(()=>{"use strict";as();Vn();is();Ga();qv()});import{existsSync as aE,promises as Ei}from"fs";import he from"path";import OD from"os";async function Lv(e){try{return await Ei.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function DD(e){try{let t=await Ei.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ss(e,t){let r=he.relative(e,t);return r===""||!he.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${he.sep}`)}async function os(e){let t=[],r=e;for(;!await Lv(r);){let n=he.dirname(r);if(n===r)break;t.push(he.basename(r)),r=n}let i=await Ei.realpath(r);return he.resolve(i,...t.reverse())}async function Vv(e){try{return(await Ei.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wf(e){let t=he.resolve(e);try{(await Ei.stat(t)).isDirectory()||(t=he.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=he.resolve(OD.homedir());for(;;){if(!(t===i&&r!==i)){let o=he.join(t,...cl.split("/")),s=t===r||await DD(o);if(await Lv(o)&&s)return t}if(await Lv(he.join(t,".git")))return t;let a=he.dirname(t);if(a===t)return r;t=a}}function zn(e){return Wa(e)}async function BD(e,t){let r=zn(t),i=he.resolve(e,...r.split("/")),n=await Ei.realpath(e),a=await os(i);if(!ss(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function pe(e,t){let r=zn(t),i=await BD(e,r),n=he.join(i,"comet");if(await Vv(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([os(i),os(n)]);if(!ss(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=he.resolve(e),c=he.join(s,".comet","runtime","native");if(await Vv(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ei.realpath(s),os(c)]);if(!ss(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:he.join(e,...cl.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:he.join(n,"specs"),changesDir:he.join(n,"changes"),archiveDir:he.join(n,"archive"),runtimeDir:c,changesRuntimeDir:he.join(c,"changes"),locksDir:he.join(c,"locks"),transactionsDir:he.join(c,"transactions")}}async function yf(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await j(e.nativeRoot,t),await Ei.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await j(e.projectRoot,t),await Ei.mkdir(t,{recursive:!0})}))}function sE(e){if(!HD.test(e))throw new Error(`Invalid Native change name: ${e}`)}function He(e,t){sE(t);let r=he.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Ka(e,t){sE(t);let r=he.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function V(e,t){let r=He(e,t);if(aE(r))return r;let i=Ka(e,t);return aE(i)?i:r}async function oE(e){try{let t=await Ei.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function ll(e,t){let r=He(e,t),i=Ka(e,t),[n,a]=await Promise.all([oE(r),oE(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Jn(e,t){if(!t.startsWith("runtime/")||he.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=he.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function F(e,t){let r=he.resolve(t);if(q(e.runtimeDir,r))return e.runtimeDir;if(q(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function q(e,t){return ss(he.resolve(e),he.resolve(t))}async function j(e,t){let r=he.resolve(e),i=he.resolve(t);if(!ss(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Vv(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([os(r),os(i)]);if(!ss(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var cl,HD,Q=_(()=>{"use strict";Vn();cl=".comet/config.yaml",HD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import qD from"path";function Ya(e="docs",t="en"){return lf(e,t)}async function X(e){let t=(await hf(e))?.config??null;return t?.native?t:null}async function cs(e){let t=await X(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Nr(e,t,r={}){let i=await sl(e,{allowPartialProject:!0}),n=il(i.document?.value??{},t),a=qD.join(e,...cl.split("/"));await xe(a,rl(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Fv(e,i.identity)}})}async function lE(e){let t=await wf(e.startPath),r=await X(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${cl} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?zn(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Ya(i??"docs"),a=await pe(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Wv,Nf,cE,tt=_(()=>{"use strict";Vn();is();Mv();Oe();Q();Wv=sr,Nf=cf,cE=GS});import{AsyncLocalStorage as FD}from"async_hooks";import{randomUUID as fE}from"crypto";import{promises as $r}from"fs";import hE from"os";import Me from"path";function LD(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function VD(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function pE(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function kf(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return wr(r,i)?J(r,i):J(r,i)&&e.size===t.size}function Sf(e,t){return kf(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function WD(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Sf(e.identity,t.identity)}async function ni(e){let t,r;try{let i=await Ja(e,uE,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof ri?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${uE} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:VD(JSON.parse(t.toString("utf8")),e),identity:pE(r)}}async function zD(e){return(await ni(e))?.owner??null}function Jv(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==hE.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=XD(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function JD(e,t){try{await $r.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await $r.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ef(e,t){let r=await ni(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Sf(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await $r.mkdir(t,{recursive:!0});let i=Me.join(t,`${Me.basename(e.file)}.${e.owner.id}.${fE()}.removed`);try{await $r.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ni(i);if(!n||n.owner.id!==e.owner.id||!kf(n.identity,e.identity))throw await JD(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await $r.rm(i,{force:!0}),"removed"}function mE(e){return{id:fE(),pid:process.pid,hostname:hE.hostname(),createdAt:new Date().toISOString(),operation:e}}async function vE(e,t){let r;try{r=await $r.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await zD(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
+
`,"utf8"),await r.sync(),i=pE(await r.stat({bigint:!0}))}finally{await r.close()}let n=await ni(e);if(!i||!n||n.owner.id!==t.id||!kf(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function GD(e,t){let r=await j(e.runtimeDir,e.locksDir);await $r.mkdir(r,{recursive:!0});let i=await j(e.runtimeDir,Me.join(r,zv));await $r.mkdir(i,{recursive:!0});let n=mE(t),a=Me.join(i,`.${n.id}.tmp`),o=Me.join(i,`${n.id}.claim`);try{let s=await vE(a,n);await $r.rename(a,o);let c=await ni(o);if(!c||!kf(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await $r.rm(a,{force:!0})}}async function UD(e){let t=Me.dirname(e.file),r=!1,i=Me.basename(e.file);for(let n of await $r.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Me.join(t,n.name);if(Me.resolve(a)!==Me.resolve(e.file))try{let o=await ni(a),s=Jv(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ef(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function gE(e){let t=await ni(e.file);if(t){if(t.owner.id!==e.owner.id||!Sf(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ef(t,Me.dirname(e.file))}}async function KD(e,t){let r=Date.now()+MD;for(;;){let i=await GD(e,t);if(!await UD(i))return i;if(await gE(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function YD(e){let t=bf.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return bf.set(e,n),await t,()=>{r(),bf.get(e)===n&&bf.delete(e)}}async function Rf(e,t,r){let i=Me.resolve(e.locksDir),n=dE.getStore();if(n?.has(i))return r();let a=await YD(i);try{let o=await KD(e,t),s=new Map(n??[]);return s.set(i,o),await dE.run(s,async()=>{try{return await r()}finally{await gE(o)}})}finally{a()}}async function Xa(e,t,r){let i=[...new Map(e.map(a=>[Me.resolve(a.locksDir),a])).values()].sort((a,o)=>Me.resolve(a.locksDir).localeCompare(Me.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Rf(o,t,()=>n(a+1)):r()};return n(0)}async function Ki(e,t,r){return Rf(e,`acquire ${t}`,async()=>{let i=await j(e.runtimeDir,e.locksDir);await $r.mkdir(i,{recursive:!0});let n=await j(e.runtimeDir,Me.join(i,LD(t))),a=mE(r),o=await vE(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Yi(e){await ni(e.file)&&await Rf({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Me.basename(e.file)}`,async()=>{let t=await ni(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Sf(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Me.join(e.locksDir,zv);await Ef(t,r)})}function XD(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function ul(e){return Jv(await ni(e))}async function Gv(e,t,r){return Rf(e,`take over ${Me.basename(t)}`,async()=>{let i=await j(e.runtimeDir,e.locksDir),n=await j(e.runtimeDir,t);if(Me.resolve(Me.dirname(n))!==Me.resolve(i))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ni(n),o=Jv(a);if(o.status==="missing")return{status:"missing"};if(r&&!WD(r,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=Me.join(i,zv);return await Ef(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}var uE,zv,MD,dE,bf,Qa=_(()=>{"use strict";al();Q();Ir();uE=16*1024,zv=".coordinator",MD=5e3,dE=new FD,bf=new Map});import{createHash as QD}from"crypto";function ai(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ZD(e,t){t.has(e)&&ai("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||ai("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&ai("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ai("symbol properties are not supported"),`[${e.map(i=>Uv(i,t)).join(",")}]`}finally{t.delete(e)}}function eB(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&ai("only plain objects are supported"),t.has(e)&&ai("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ai("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&ai("accessor properties are not supported"),`${JSON.stringify(o)}:${Uv(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Uv(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||ai("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ZD(e,t):eB(e,t);case"bigint":case"function":case"symbol":case"undefined":return ai(`${typeof e} values are not supported`)}return ai("unsupported value type")}function dl(e){return Uv(e,new Set)}function B(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return QD("sha256").update(`${e}
|
|
174
|
+
${dl(t)}`).digest("hex")}var ct=_(()=>{"use strict"});import wE from"node:path";function sB(e,t){return e<t?-1:e>t?1:0}function bE(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function kE(e,t){let r=t.toString(36),i=B("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function cB(e){if(!aB.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=oB.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==B("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function lB(e,t){let r=bE(e.text,Xi.maxTextBytes),i=e.context.slice(0,Xi.maxContextItems).map(n=>bE(n,Xi.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function EE(e){let t=cB({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(sB),n=i.slice(0,Xi.maxFailedCheckIds),a=e.criteria.slice(t,t+Xi.maxItems);for(let c of a){let l=[...r,lB(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:u<e.criteria.length?kE(e.acceptanceHash,u):null,limits:{...Xi}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Xi.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?kE(e.acceptanceHash,o):null,limits:{...Xi}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Xi.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Yv(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Kv(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function SE(e){return e.includes("-->")||e.includes("--!>")}function*ls(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
175
175
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
176
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Kv(l,t);else if(r)SE(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Kv(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!SE(f))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function uB(e){return[...ls(e)].map(({line:t,body:r})=>({line:t,body:r}))}function fl(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function dB(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Xv(e,t,r,i=[],n="content-hash"){let a=fl(r),o=t.replaceAll("\\","/").trim(),s=i.map(fl);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${
|
|
176
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Kv(l,t);else if(r)SE(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Kv(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!SE(f))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function uB(e){return[...ls(e)].map(({line:t,body:r})=>({line:t,body:r}))}function fl(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function dB(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Xv(e,t,r,i=[],n="content-hash"){let a=fl(r),o=t.replaceAll("\\","/").trim(),s=i.map(fl);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${B(tB,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Qv(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function fB(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of ls(e)){n=s+1;let c=o?Yv(a):null;c?.level===1&&(nf(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Pf(e,t="brief.md",r=hl.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=fB(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of ls(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of ls(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),Qv(o.map(l=>Xv("brief-example",t,l.join(`
|
|
177
177
|
`),[],i)),"Brief",i)}function Cf(e,t="spec.md",r=hl.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Xv("spec-scenario",t,[o.title,...o.body].join(`
|
|
178
178
|
`),o.context,i)),o=null}};for(let{line:c,body:l}of ls(e)){let u=l?Yv(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=fl(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),Qv(n,"Specification",i)}function RE(e,t="spec.md",r=hl.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Xv("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of ls(e)){let f=d?Yv(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let p=u.trim();if(!d||o!==null||l()){c();continue}if(p.length===0||Kv(u,null)!==null||p.startsWith("<!--")||p==="-->"||p==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(p)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(p)||/^(?:[-*_]\s*){3,}$/u.test(p)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(p)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(h=>h.text)};continue}if(/^\|.*\|$/u.test(p)){c(),s={parts:[p],context:a.map(h=>h.text)},c();continue}s===null?s={parts:[p],context:a.map(h=>h.text)}:s.parts.push(p)}return c(),Qv(n,"Specification mandatory requirements",i)}function hB(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||dB(r)||wE.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=wE.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!nB.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function pB(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!iB.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function PE(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=pB(r,i),a=n.acceptance_id;if(typeof a!="string"||!rB.test(a))throw new Error(`Acceptance evidence entry ${i} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.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 hB(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.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 CE(e){let t=uB(e);if(t.some(({line:l,body:u})=>!u&&(l===yE||l===NE)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===yE?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===NE?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
179
|
-
`).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=PE(o),c=mB(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function mB(e){let t=PE([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var tB,rB,iB,nB,aB,oB,Yi,hl,yE,NE,pl=_(()=>{"use strict";Va();ct();tB="comet.native.acceptance.v1",rB=/^acceptance-[a-f0-9]{64}$/u,iB=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),nB=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,aB=/^[a-f0-9]{64}$/u,oB=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;Yi=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),hl=Object.freeze({maxCriteria:1024}),yE="<!-- comet-native:acceptance-evidence:start -->",NE="<!-- comet-native:acceptance-evidence:end -->"});import xE from"node:path";function AE(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||xE.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||xE.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function gB(e,t){return e.localeCompare(t,"en")}function xf(e){let t=AE(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>gB(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Pf(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=AE(a.source,`Native spec source for ${a.capability}`);i.push(...Cf(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=fl(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function _E(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!vB.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Zv(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var vB,Af=_(()=>{"use strict";pl();vB=/^A[1-9]\d*$/u});function If(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Za,ml,_f,us=_(()=>{"use strict";Za="comet.native.v4",ml="comet.native.local-execution.v4",_f=["multi-session","single-session"]});var ng={};ed(ng,{NativePortableStateVersionConflictError:()=>vl,appendNativePortableHistory:()=>Pt,compareAndSwapNativePortableState:()=>Gn,createNativePortableState:()=>ig,parseNativePortableState:()=>z,readNativePortableState:()=>Rt,writeNativePortableState:()=>hs});import{promises as wB}from"node:fs";function Gt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ut(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ht(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function tg(e,t){return e===null?null:ht(e,t)}function IE(e,t){let r=ht(e,t);if(!kB.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ds(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Le(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function EB(e,t){return e===null?null:Le(e,t,Number.MIN_SAFE_INTEGER)}function rt(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ei(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function $f(e,t){return Ei(e,t,(r,i)=>ht(r,`${t}[${i}]`))}function eo(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function fs(e,t){let r=ht(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function rg(e,t,r=!1){let i=ht(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Or(e,t){let r=Gt(e,t);return Ut(r,new Set(["text","truncated"]),t),{text:ht(r.text,`${t}.text`,{empty:!0}),truncated:ds(r.truncated,`${t}.truncated`)}}function RB(e,t){let r=`Native spec_changes[${t}]`,i=Gt(e,r);Ut(i,new Set(["capability","operation","source"]),r);let n=ht(i.capability,`${r}.capability`);if(!NB.test(n))throw new Error(`${r}.capability is invalid`);let a=rt(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:rg(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function PB(e){let t="Native workspace",r=Gt(e,t);Ut(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=rt(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=tg(r.change_branch,`${t}.change_branch`),a=tg(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:rt(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function CB(e){let t="Native loop",r=Gt(e,t);Ut(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=$f(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);eo(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:rt(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:rt(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:Le(r.goal_cycle,`${t}.goal_cycle`,1),iteration:Le(r.iteration,`${t}.iteration`),attempt:Le(r.attempt,`${t}.attempt`),retry_epoch:Le(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:Le(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:Le(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:Le(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:tg(r.next_action,`${t}.next_action`)}}function xB(e,t){let r=`Native acceptance[${t}]`,i=Gt(e,r);Ut(i,new Set(["id","source","text","result","reason"]),r);let n=ht(i.id,`${r}.id`);if(!bB.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:rg(i.source,`${r}.source`),text:ht(i.text,`${r}.text`),result:rt(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Or(i.reason,`${r}.reason`)}}function AB(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Gt(e,r);return Ut(i,new Set(["name","result","note"]),r),{name:Or(i.name,`${r}.name`),result:rt(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Or(i.note,`${r}.note`)}}function _B(e){let t="Native builder_handoff",r=Gt(e,t);Ut(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=$f(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);eo(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Gt(r.review,`${t}.review`);return n&&Ut(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ht(r.candidate_id,`${t}.candidate_id`),identity_provider:ht(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ht(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:Le(r.iteration,`${t}.iteration`,1),summary:Or(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ei(r.checks,`${t}.checks`,AB),checks_truncated:ds(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ei(r.known_limits,`${t}.known_limits`,(a,o)=>Or(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ds(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:rt(n.status,["passed"],`${t}.review.status`),summary:Or(n.summary,`${t}.review.summary`),reviewer_execution_ref:ht(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:fs(r.submitted_at,`${t}.submitted_at`)}}function IB(e,t){let r=`Native blockers[${t}]`,i=Gt(e,r);Ut(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=$f(i.acceptance_ids,`${r}.acceptance_ids`);return eo(n,`${r}.acceptance_ids`),{owner:rt(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Or(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:rt(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function TB(e,t){let r=`Native verification.checks[${t}]`,i=Gt(e,r);return Ut(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ht(i.id,`${r}.id`),name:Or(i.name,`${r}.name`),argv_display:Ei(i.argv_display,`${r}.argv_display`,(n,a)=>Or(n,`${r}.argv_display[${a}]`)),argv_truncated:ds(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:rg(i.cwd_ref,`${r}.cwd_ref`,!0),status:rt(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:EB(i.exit_code,`${r}.exit_code`),duration_ms:Le(i.duration_ms,`${r}.duration_ms`)}}function jB(e){let t="Native verification",r=Gt(e,t);Ut(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ei(r.checks,`${t}.checks`,TB);eo(i.map(a=>a.id),`${t}.checks IDs`);let n=ht(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ht(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ht(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:Le(r.iteration,`${t}.iteration`,1),attempt:Le(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":rt(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:rt(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Or(r.summary,`${t}.summary`),risks:Ei(r.risks,`${t}.risks`,(a,o)=>Or(a,`${t}.risks[${o}]`)),risks_truncated:ds(r.risks_truncated,`${t}.risks_truncated`),completed_at:fs(r.completed_at,`${t}.completed_at`)}}function TE(e,t){let r=`Native history[${t}]`,i=Gt(e,r);Ut(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=$f(i.unresolved_ids,`${r}.unresolved_ids`);return eo(n,`${r}.unresolved_ids`),{goal_cycle:Le(i.goal_cycle,`${r}.goal_cycle`,1),iteration:Le(i.iteration,`${r}.iteration`),attempt:Le(i.attempt,`${r}.attempt`),outcome:rt(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Or(i.summary,`${r}.summary`),completed_at:fs(i.completed_at,`${r}.completed_at`)}}function $B(e){let t="Native history_overflow.outcome_counts",r=Gt(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ut(r,new Set(i),t),{pass:Le(r.pass,`${t}.pass`),fail:Le(r.fail,`${t}.fail`),blocked:Le(r.blocked,`${t}.blocked`),"execution-error":Le(r["execution-error"],`${t}.execution-error`),recovery:Le(r.recovery,`${t}.recovery`)}}function OB(e){let t="Native history_overflow",r=Gt(e,t);Ut(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=Le(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:fs(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:fs(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=$B(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function HB(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function DB(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function z(e){let t=Gt(e,"Native portable state");if(Ut(t,SB,"Native portable state"),t.schema!==Za)throw new Error(`Native portable state schema must be ${Za}`);let r=ht(t.name,"Native state name");if(!yB.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ei(t.spec_changes,"Native spec_changes",RB);eo(i.map(s=>s.capability),"Native spec change capabilities");let n=Ei(t.acceptance,"Native acceptance",xB);eo(n.map(s=>s.id),"Native acceptance IDs");let a=Ei(t.history,"Native history",TE);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Za,name:r,language:rt(t.language,["en","zh-CN"],"Native state language"),phase:rt(t.phase,["shape","build","verify","archive"],"Native state phase"),status:rt(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:Le(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:IE(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:IE(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:rt(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:PB(t.workspace),loop:CB(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:_B(t.builder_handoff),blockers:Ei(t.blockers,"Native blockers",IB),verification:t.verification===null?null:jB(t.verification),history:a,history_overflow:OB(t.history_overflow),verification_result:rt(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:rt(t.verification_report,["verification.md"],"Native verification_report"),archived:ds(t.archived,"Native archived"),created_at:fs(t.created_at,"Native created_at")};return HB(o),DB(o),o}function ig(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return z({schema:Za,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:If(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Pt(e,t){let r=z(e),i=TE(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return z({...r,history:n,history_overflow:a})}function BB(e,t){let r=(0,jf.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Rt(e){let t=await wB.readFile(e,"utf8");return z(BB(t,"Native portable state"))}async function hs(e,t,r={}){let i=z(t);await xe(e,(0,jf.stringify)(i),r)}async function qB(e,t){let r=Tf.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Tf.set(e,a),await r;try{return await t()}finally{i(),Tf.get(e)===a&&Tf.delete(e)}}async function Gn(e){return qB(e.file,async()=>{let t=Le(e.expectedStateVersion,"Native expected state version",1),r=z(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Rt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new vl(t,i.state_version);return await hs(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Rt(e.file);if(n.state_version!==t)throw new vl(t,n.state_version)}}),r})}var jf,yB,NB,bB,kB,SB,vl,Tf,ai=_(()=>{"use strict";jf=Ha(Mn(),1);$e();us();yB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bB=/^A[1-9][0-9]*$/u,kB=/^[a-f0-9]{64}$/u,SB=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),vl=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Tf=new Map});function FB(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ke(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(FB(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var gl=_(()=>{"use strict"});var Ye,Xe,Kt,Un,Xi,to,wl=_(()=>{"use strict";Ye="comet.native.v3",Xe="comet.native.v2",Kt="comet.native.v1",Un="comet.native.transition.v3",Xi="comet.native.transition.v2",to="comet.native.transition.v1"});import MB from"node:path";function GB(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function UB(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function KB(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function YB(e){return e.schema===Kt?ro(e):e.schema===Xe?Ri(e):cr(e)}function XB(e){return MB.posix.normalize(e.replaceAll("\\","/"))}function QB(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:XB(t.source)})}function ZB(e){return e==="shape"?"shape":"build"}function eq(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function tq(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function jE(e){let t=YB(e.state);_E(e.acceptance);let r=ZB(t.phase),i=r==="shape"?0:1,n=UB(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return z({schema:Za,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:QB(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:eq(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ke(tq(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:If(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ag(e){let t=GB(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!LB.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Of)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!WB.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!VB.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!JB.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!zB.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Of,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:KB(t.createdAt,"Native portable migration transaction createdAt")}}function $E(e){switch(ag(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Of,LB,VB,WB,zB,JB,og=_(()=>{"use strict";Ee();Af();ai();gl();us();wl();Of="comet.native.portable-migration.v1",LB=new Set(["schema","id","change","fromSchema","status","createdAt"]),VB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WB=/^[a-z0-9][a-z0-9-]{7,127}$/u,zB=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),JB=new Set([Kt,Xe,Ye])});import{promises as rq}from"node:fs";import sg from"node:path";function DE(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function BE(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function uq(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=DE(e,r);if(BE(i,lq,r),typeof i.capability!="string"||!HE.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function dq(e){let t=DE(e,"Native portable Archive transaction");if(BE(t,cq,"Native portable Archive transaction"),t.schema!==Hf)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!aq.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!HE.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!oq.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!sq.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(uq);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Hf,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function io(e){let t=iq.exec(e);if(t)return{kind:"archive",change:t[1]};let r=nq.exec(e);return r?{kind:"migration",change:r[1]}:null}function Kn(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=io(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return sg.join(e.transactionsDir,r)}async function yl(e,t){let r=io(t);if(!r)return null;let i=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=sg.join(e.transactionsDir,t);if(r.kind==="archive"){let s=dq(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=ag(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Yn(e,t){let r=Kn(e,t);try{return await yl(e,sg.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}async function qE(e){let t;try{t=await rq.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.map(({name:r})=>r).filter(r=>io(r)!==null).sort((r,i)=>r.localeCompare(i,"en"))}function FE(e){return e.kind==="archive"||e.journal.status!=="committed"}var Hf,OE,iq,nq,aq,oq,sq,cq,lq,HE,no=_(()=>{"use strict";Jt();og();Hf="comet.native.archive-transaction.v4",OE="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",iq=new RegExp(`^portable-archive-(${OE})\\.json$`,"u"),nq=new RegExp(`^portable-migration-(${OE})\\.json$`,"u"),aq=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,oq=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sq=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),cq=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),lq=new Set(["capability","operation","source","content"]),HE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as fq}from"node:crypto";import{constants as Df,promises as ie}from"node:fs";import me from"node:path";import{TextDecoder as hq}from"node:util";function Ot(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function ME(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ms(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function LE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ps(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Xn(e,t){let r=await ie.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ie.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Qn(e,t,r){let i=me.resolve(e),n=me.resolve(t);if(!Ot(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Xn(i,r)],o=i;for(let s of me.relative(i,n).split(me.sep).filter(Boolean)){await ze(a,r),o=me.join(o,s);let c=await Xn(o,r);if(!Ot(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await ze(a,r),a}async function ze(e,t){for(let r of e){let i=await ie.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ms(r,i)||await ie.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function pq(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Ie(e){let t=ME(e.maxBytes),r=me.resolve(e.file),i=await Qn(e.root,me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Xn(me.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ze(i,e.label);let a=await ie.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=LE(a),s=await ie.realpath(r);if(!Ot(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Ot(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Df.O_RDONLY:Df.O_RDONLY|Df.O_NOFOLLOW|Df.O_NONBLOCK,l=await ie.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([ie.lstat(r),ie.realpath(r)]);if(await ze(i,e.label),await ze(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ps(o,u)||!ps(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await pq(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),ie.lstat(r),ie.realpath(r)]);if(await ze(i,e.label),await ze(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!ps(o,v)||!ps(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:fq("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Bf(e){let t=await Ie(e),r;try{r=new hq("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function lr(e){let t=await Qn(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await ie.readdir(e.directory,{withFileTypes:!0});else{let i=ME(e.maxEntries);r=[];let n=await ie.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ze(t,e.label),{entries:r,verify:()=>ze(t,e.label)}}async function br(e){let t=await Qn(e.root,e.directory,e.label);return{verify:()=>ze(t,e.label)}}async function mq(e){let t=me.resolve(e.directory),r=me.resolve(e.quarantine);if(me.dirname(r)!==me.dirname(t)||!Ot(me.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let i=await Qn(e.root,me.dirname(t),e.label),n=await Xn(t,e.label);if(!Ot(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ze(i,e.label);let a=await ie.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!ms(n,a)||await ie.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await ie.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await ie.rename(t,r),await ze(i,e.label);let o=await ie.lstat(r);if(!o.isDirectory()||o.isSymbolicLink()||!ms(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await ie.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:i,identity:n}}async function VE(e){await mq(e)}async function qf(e){let t=me.resolve(e.file),r=await Qn(e.root,me.dirname(t),e.label),i=await ie.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=LE(i),a=await ie.realpath(t);if(!Ot(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await Ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([ie.lstat(t),ie.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!ps(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ze(r,e.label);let[l,u]=await Promise.all([ie.lstat(t),ie.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!ps(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await ie.rm(t),await ze(r,e.label)}async function cg(e){let t=me.resolve(e.directory),r=await Qn(e.root,me.dirname(t),e.label),i=await Xn(t,e.label);if(!Ot(r[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ze(r,e.label);let n=await ie.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!ms(i,n)||await ie.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before removal`);await ie.rmdir(t),await ze(r,e.label)}async function Pi(e){let t=me.resolve(e.root),r=me.resolve(e.directory);if(!Ot(t,r))throw new Error(`${e.label} is outside its managed root`);let i=[await Xn(t,e.label)],n=t;for(let a of me.relative(t,r).split(me.sep).filter(Boolean)){await ze(i,e.label),n=me.join(n,a);try{await ie.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Xn(n,e.label);if(!Ot(i[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);i.push(o)}await ze(i,e.label)}async function lg(e){let t=me.resolve(e.root),r=me.resolve(e.source),i=me.resolve(e.target);if(r===i||!Ot(t,r)||!Ot(t,i)||Ot(r,i)||Ot(i,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Pi({root:t,directory:me.dirname(i),label:`${e.label} target parent`});let n=await Qn(t,me.dirname(r),e.label),a=await Qn(t,me.dirname(i),e.label),o=await Xn(r,e.label);if(!Ot(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await ie.lstat(i),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ze(n,e.label),ze(a,e.label)]);let s=await ie.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!ms(o,s)||await ie.realpath(r)!==o.realPath)throw new Error(`${e.label} source changed before move`);await ie.rename(r,i),await Promise.all([ze(n,e.label),ze(a,e.label)]);let c=await ie.lstat(i);if(!c.isDirectory()||c.isSymbolicLink()||!ms(o,c)||!Ot(n[0].realPath,await ie.realpath(i)))throw new Error(`${e.label} source identity changed while moving`);try{throw await ie.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Zn(e){let t=await Ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await GN(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await ie.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await Ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let r=await Ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}var Yt=_(()=>{"use strict";$e();Ir()});import{promises as Nl}from"fs";import Hr from"path";import{TextDecoder as vq}from"util";function bl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function kl(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function gs(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ug(e,t){if(typeof e!="string"||e.length===0||Hr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ff(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function WE(e,t){if(ug(e,t),e.includes("\\")||e!==Hr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function Rq(e,t){let r=bl(e,`transaction operations[${t}]`);if(kl(r,wq,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ug(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ug(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Vf(e){let t=bl(e,"Native Archive transaction journal");if(kl(t,yq,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!GE.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!gs(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ff(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=bl(s,`Archive transaction operations[${c}]`);if(kl(l,Nq,`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`);WE(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&WE(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ff(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(Ff(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`);Ff(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.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 r.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(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function hg(e){let t=bl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Vf(t);if(kl(t,gq,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!GE.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Hr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Hr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!gs(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(Rq),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function XE(e,t){let r=bl(e,`Native transaction event at line ${t}`);if(kl(r,bq,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!gs(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!UE.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let i=r.type==="operation-started"||r.type==="operation-completed";if(i&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!i&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function Pq(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let i=0;i<e.length;i+=1){let n=t[i],a=e[i];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let r=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[i,n,a,o]of r){if(e.length<=i)continue;let s=e.slice(i,Math.min(i+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!gs(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||gs(e)}function vs(e,t){return e.length<t.length&&t.startsWith(e)}function Cq(e){let t='","operationId":"';if(vs(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf('"');if(i===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let n=r.slice(0,i);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?vs(r.slice(i),'"}'):!1}function xq(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>KE)return!1;let r=`{"sequence":${t},"timestamp":"`;if(vs(e,r))return!0;if(!e.startsWith(r))return!1;let i=e.slice(r.length),n=i.slice(0,Math.min(24,i.length));if(!Pq(n))return!1;if(i.length<24)return!0;if(!gs(n))return!1;let a='","type":"',o=i.slice(24);if(vs(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of UE){if(vs(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(Cq(l))return!0}else if(vs(l,'"}'))return!0}return!1}function Aq(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>KE)throw new Error(`Native transaction event at line ${t} is too large`);return XE(JSON.parse(e),t)}function _q(e){let t=e.split(`
|
|
179
|
+
`).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=PE(o),c=mB(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function mB(e){let t=PE([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var tB,rB,iB,nB,aB,oB,Xi,hl,yE,NE,pl=_(()=>{"use strict";Va();ct();tB="comet.native.acceptance.v1",rB=/^acceptance-[a-f0-9]{64}$/u,iB=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),nB=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,aB=/^[a-f0-9]{64}$/u,oB=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;Xi=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),hl=Object.freeze({maxCriteria:1024}),yE="<!-- comet-native:acceptance-evidence:start -->",NE="<!-- comet-native:acceptance-evidence:end -->"});import xE from"node:path";function AE(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||xE.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||xE.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function gB(e,t){return e.localeCompare(t,"en")}function xf(e){let t=AE(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>gB(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Pf(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=AE(a.source,`Native spec source for ${a.capability}`);i.push(...Cf(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=fl(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function _E(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!vB.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Zv(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var vB,Af=_(()=>{"use strict";pl();vB=/^A[1-9]\d*$/u});function If(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Za,ml,_f,us=_(()=>{"use strict";Za="comet.native.v4",ml="comet.native.local-execution.v4",_f=["multi-session","single-session"]});var ng={};ed(ng,{NativePortableStateVersionConflictError:()=>vl,appendNativePortableHistory:()=>Pt,compareAndSwapNativePortableState:()=>Gn,createNativePortableState:()=>ig,parseNativePortableState:()=>z,readNativePortableState:()=>Rt,writeNativePortableState:()=>hs});import{promises as wB}from"node:fs";function Gt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ut(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ht(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function tg(e,t){return e===null?null:ht(e,t)}function IE(e,t){let r=ht(e,t);if(!kB.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ds(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Le(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function EB(e,t){return e===null?null:Le(e,t,Number.MIN_SAFE_INTEGER)}function rt(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ri(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function $f(e,t){return Ri(e,t,(r,i)=>ht(r,`${t}[${i}]`))}function eo(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function fs(e,t){let r=ht(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function rg(e,t,r=!1){let i=ht(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Or(e,t){let r=Gt(e,t);return Ut(r,new Set(["text","truncated"]),t),{text:ht(r.text,`${t}.text`,{empty:!0}),truncated:ds(r.truncated,`${t}.truncated`)}}function RB(e,t){let r=`Native spec_changes[${t}]`,i=Gt(e,r);Ut(i,new Set(["capability","operation","source"]),r);let n=ht(i.capability,`${r}.capability`);if(!NB.test(n))throw new Error(`${r}.capability is invalid`);let a=rt(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:rg(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function PB(e){let t="Native workspace",r=Gt(e,t);Ut(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=rt(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=tg(r.change_branch,`${t}.change_branch`),a=tg(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:rt(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function CB(e){let t="Native loop",r=Gt(e,t);Ut(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=$f(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);eo(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:rt(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:rt(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:Le(r.goal_cycle,`${t}.goal_cycle`,1),iteration:Le(r.iteration,`${t}.iteration`),attempt:Le(r.attempt,`${t}.attempt`),retry_epoch:Le(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:Le(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:Le(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:Le(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:tg(r.next_action,`${t}.next_action`)}}function xB(e,t){let r=`Native acceptance[${t}]`,i=Gt(e,r);Ut(i,new Set(["id","source","text","result","reason"]),r);let n=ht(i.id,`${r}.id`);if(!bB.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:rg(i.source,`${r}.source`),text:ht(i.text,`${r}.text`),result:rt(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Or(i.reason,`${r}.reason`)}}function AB(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Gt(e,r);return Ut(i,new Set(["name","result","note"]),r),{name:Or(i.name,`${r}.name`),result:rt(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Or(i.note,`${r}.note`)}}function _B(e){let t="Native builder_handoff",r=Gt(e,t);Ut(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=$f(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);eo(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Gt(r.review,`${t}.review`);return n&&Ut(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ht(r.candidate_id,`${t}.candidate_id`),identity_provider:ht(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ht(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:Le(r.iteration,`${t}.iteration`,1),summary:Or(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ri(r.checks,`${t}.checks`,AB),checks_truncated:ds(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ri(r.known_limits,`${t}.known_limits`,(a,o)=>Or(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ds(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:rt(n.status,["passed"],`${t}.review.status`),summary:Or(n.summary,`${t}.review.summary`),reviewer_execution_ref:ht(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:fs(r.submitted_at,`${t}.submitted_at`)}}function IB(e,t){let r=`Native blockers[${t}]`,i=Gt(e,r);Ut(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=$f(i.acceptance_ids,`${r}.acceptance_ids`);return eo(n,`${r}.acceptance_ids`),{owner:rt(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Or(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:rt(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function TB(e,t){let r=`Native verification.checks[${t}]`,i=Gt(e,r);return Ut(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ht(i.id,`${r}.id`),name:Or(i.name,`${r}.name`),argv_display:Ri(i.argv_display,`${r}.argv_display`,(n,a)=>Or(n,`${r}.argv_display[${a}]`)),argv_truncated:ds(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:rg(i.cwd_ref,`${r}.cwd_ref`,!0),status:rt(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:EB(i.exit_code,`${r}.exit_code`),duration_ms:Le(i.duration_ms,`${r}.duration_ms`)}}function jB(e){let t="Native verification",r=Gt(e,t);Ut(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ri(r.checks,`${t}.checks`,TB);eo(i.map(a=>a.id),`${t}.checks IDs`);let n=ht(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ht(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ht(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:Le(r.iteration,`${t}.iteration`,1),attempt:Le(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":rt(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:rt(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Or(r.summary,`${t}.summary`),risks:Ri(r.risks,`${t}.risks`,(a,o)=>Or(a,`${t}.risks[${o}]`)),risks_truncated:ds(r.risks_truncated,`${t}.risks_truncated`),completed_at:fs(r.completed_at,`${t}.completed_at`)}}function TE(e,t){let r=`Native history[${t}]`,i=Gt(e,r);Ut(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=$f(i.unresolved_ids,`${r}.unresolved_ids`);return eo(n,`${r}.unresolved_ids`),{goal_cycle:Le(i.goal_cycle,`${r}.goal_cycle`,1),iteration:Le(i.iteration,`${r}.iteration`),attempt:Le(i.attempt,`${r}.attempt`),outcome:rt(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Or(i.summary,`${r}.summary`),completed_at:fs(i.completed_at,`${r}.completed_at`)}}function $B(e){let t="Native history_overflow.outcome_counts",r=Gt(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ut(r,new Set(i),t),{pass:Le(r.pass,`${t}.pass`),fail:Le(r.fail,`${t}.fail`),blocked:Le(r.blocked,`${t}.blocked`),"execution-error":Le(r["execution-error"],`${t}.execution-error`),recovery:Le(r.recovery,`${t}.recovery`)}}function OB(e){let t="Native history_overflow",r=Gt(e,t);Ut(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=Le(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:fs(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:fs(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=$B(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function HB(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function DB(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function z(e){let t=Gt(e,"Native portable state");if(Ut(t,SB,"Native portable state"),t.schema!==Za)throw new Error(`Native portable state schema must be ${Za}`);let r=ht(t.name,"Native state name");if(!yB.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ri(t.spec_changes,"Native spec_changes",RB);eo(i.map(s=>s.capability),"Native spec change capabilities");let n=Ri(t.acceptance,"Native acceptance",xB);eo(n.map(s=>s.id),"Native acceptance IDs");let a=Ri(t.history,"Native history",TE);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Za,name:r,language:rt(t.language,["en","zh-CN"],"Native state language"),phase:rt(t.phase,["shape","build","verify","archive"],"Native state phase"),status:rt(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:Le(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:IE(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:IE(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:rt(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:PB(t.workspace),loop:CB(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:_B(t.builder_handoff),blockers:Ri(t.blockers,"Native blockers",IB),verification:t.verification===null?null:jB(t.verification),history:a,history_overflow:OB(t.history_overflow),verification_result:rt(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:rt(t.verification_report,["verification.md"],"Native verification_report"),archived:ds(t.archived,"Native archived"),created_at:fs(t.created_at,"Native created_at")};return HB(o),DB(o),o}function ig(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return z({schema:Za,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:If(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Pt(e,t){let r=z(e),i=TE(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return z({...r,history:n,history_overflow:a})}function BB(e,t){let r=(0,jf.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Rt(e){let t=await wB.readFile(e,"utf8");return z(BB(t,"Native portable state"))}async function hs(e,t,r={}){let i=z(t);await xe(e,(0,jf.stringify)(i),r)}async function qB(e,t){let r=Tf.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Tf.set(e,a),await r;try{return await t()}finally{i(),Tf.get(e)===a&&Tf.delete(e)}}async function Gn(e){return qB(e.file,async()=>{let t=Le(e.expectedStateVersion,"Native expected state version",1),r=z(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Rt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new vl(t,i.state_version);return await hs(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Rt(e.file);if(n.state_version!==t)throw new vl(t,n.state_version)}}),r})}var jf,yB,NB,bB,kB,SB,vl,Tf,oi=_(()=>{"use strict";jf=Ha(Mn(),1);Oe();us();yB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bB=/^A[1-9][0-9]*$/u,kB=/^[a-f0-9]{64}$/u,SB=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),vl=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};Tf=new Map});function FB(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ke(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(FB(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var gl=_(()=>{"use strict"});var Ye,Xe,Kt,Un,Qi,to,wl=_(()=>{"use strict";Ye="comet.native.v3",Xe="comet.native.v2",Kt="comet.native.v1",Un="comet.native.transition.v3",Qi="comet.native.transition.v2",to="comet.native.transition.v1"});import MB from"node:path";function GB(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function UB(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function KB(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function YB(e){return e.schema===Kt?ro(e):e.schema===Xe?Pi(e):cr(e)}function XB(e){return MB.posix.normalize(e.replaceAll("\\","/"))}function QB(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:XB(t.source)})}function ZB(e){return e==="shape"?"shape":"build"}function eq(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function tq(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function jE(e){let t=YB(e.state);_E(e.acceptance);let r=ZB(t.phase),i=r==="shape"?0:1,n=UB(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return z({schema:Za,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:QB(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:eq(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:ke(tq(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:If(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ag(e){let t=GB(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!LB.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Of)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!WB.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!VB.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!JB.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!zB.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Of,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:KB(t.createdAt,"Native portable migration transaction createdAt")}}function $E(e){switch(ag(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Of,LB,VB,WB,zB,JB,og=_(()=>{"use strict";Ee();Af();oi();gl();us();wl();Of="comet.native.portable-migration.v1",LB=new Set(["schema","id","change","fromSchema","status","createdAt"]),VB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WB=/^[a-z0-9][a-z0-9-]{7,127}$/u,zB=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),JB=new Set([Kt,Xe,Ye])});import{promises as rq}from"node:fs";import sg from"node:path";function DE(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function BE(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function uq(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=DE(e,r);if(BE(i,lq,r),typeof i.capability!="string"||!HE.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function dq(e){let t=DE(e,"Native portable Archive transaction");if(BE(t,cq,"Native portable Archive transaction"),t.schema!==Hf)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!aq.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!HE.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!oq.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!sq.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(uq);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Hf,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function io(e){let t=iq.exec(e);if(t)return{kind:"archive",change:t[1]};let r=nq.exec(e);return r?{kind:"migration",change:r[1]}:null}function Kn(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=io(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return sg.join(e.transactionsDir,r)}async function yl(e,t){let r=io(t);if(!r)return null;let i=await re({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=sg.join(e.transactionsDir,t);if(r.kind==="archive"){let s=dq(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=ag(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Yn(e,t){let r=Kn(e,t);try{return await yl(e,sg.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}async function qE(e){let t;try{t=await rq.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.map(({name:r})=>r).filter(r=>io(r)!==null).sort((r,i)=>r.localeCompare(i,"en"))}function FE(e){return e.kind==="archive"||e.journal.status!=="committed"}var Hf,OE,iq,nq,aq,oq,sq,cq,lq,HE,no=_(()=>{"use strict";Jt();og();Hf="comet.native.archive-transaction.v4",OE="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",iq=new RegExp(`^portable-archive-(${OE})\\.json$`,"u"),nq=new RegExp(`^portable-migration-(${OE})\\.json$`,"u"),aq=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,oq=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sq=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),cq=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),lq=new Set(["capability","operation","source","content"]),HE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as fq}from"node:crypto";import{constants as Df,promises as ie}from"node:fs";import me from"node:path";import{TextDecoder as hq}from"node:util";function Ot(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function ME(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ms(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function LE(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ps(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Xn(e,t){let r=await ie.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ie.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Qn(e,t,r){let i=me.resolve(e),n=me.resolve(t);if(!Ot(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Xn(i,r)],o=i;for(let s of me.relative(i,n).split(me.sep).filter(Boolean)){await ze(a,r),o=me.join(o,s);let c=await Xn(o,r);if(!Ot(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await ze(a,r),a}async function ze(e,t){for(let r of e){let i=await ie.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ms(r,i)||await ie.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function pq(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Te(e){let t=ME(e.maxBytes),r=me.resolve(e.file),i=await Qn(e.root,me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Xn(me.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ze(i,e.label);let a=await ie.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=LE(a),s=await ie.realpath(r);if(!Ot(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Ot(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Df.O_RDONLY:Df.O_RDONLY|Df.O_NOFOLLOW|Df.O_NONBLOCK,l=await ie.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([ie.lstat(r),ie.realpath(r)]);if(await ze(i,e.label),await ze(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ps(o,u)||!ps(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await pq(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([l.stat(),ie.lstat(r),ie.realpath(r)]);if(await ze(i,e.label),await ze(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!ps(o,v)||!ps(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:fq("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function Bf(e){let t=await Te(e),r;try{r=new hq("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function lr(e){let t=await Qn(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await ie.readdir(e.directory,{withFileTypes:!0});else{let i=ME(e.maxEntries);r=[];let n=await ie.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ze(t,e.label),{entries:r,verify:()=>ze(t,e.label)}}async function br(e){let t=await Qn(e.root,e.directory,e.label);return{verify:()=>ze(t,e.label)}}async function mq(e){let t=me.resolve(e.directory),r=me.resolve(e.quarantine);if(me.dirname(r)!==me.dirname(t)||!Ot(me.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let i=await Qn(e.root,me.dirname(t),e.label),n=await Xn(t,e.label);if(!Ot(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ze(i,e.label);let a=await ie.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!ms(n,a)||await ie.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await ie.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await ie.rename(t,r),await ze(i,e.label);let o=await ie.lstat(r);if(!o.isDirectory()||o.isSymbolicLink()||!ms(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await ie.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:i,identity:n}}async function VE(e){await mq(e)}async function qf(e){let t=me.resolve(e.file),r=await Qn(e.root,me.dirname(t),e.label),i=await ie.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=LE(i),a=await ie.realpath(t);if(!Ot(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await Te({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([ie.lstat(t),ie.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!ps(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ze(r,e.label);let[l,u]=await Promise.all([ie.lstat(t),ie.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!ps(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await ie.rm(t),await ze(r,e.label)}async function cg(e){let t=me.resolve(e.directory),r=await Qn(e.root,me.dirname(t),e.label),i=await Xn(t,e.label);if(!Ot(r[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ze(r,e.label);let n=await ie.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!ms(i,n)||await ie.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before removal`);await ie.rmdir(t),await ze(r,e.label)}async function Ci(e){let t=me.resolve(e.root),r=me.resolve(e.directory);if(!Ot(t,r))throw new Error(`${e.label} is outside its managed root`);let i=[await Xn(t,e.label)],n=t;for(let a of me.relative(t,r).split(me.sep).filter(Boolean)){await ze(i,e.label),n=me.join(n,a);try{await ie.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Xn(n,e.label);if(!Ot(i[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);i.push(o)}await ze(i,e.label)}async function lg(e){let t=me.resolve(e.root),r=me.resolve(e.source),i=me.resolve(e.target);if(r===i||!Ot(t,r)||!Ot(t,i)||Ot(r,i)||Ot(i,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Ci({root:t,directory:me.dirname(i),label:`${e.label} target parent`});let n=await Qn(t,me.dirname(r),e.label),a=await Qn(t,me.dirname(i),e.label),o=await Xn(r,e.label);if(!Ot(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await ie.lstat(i),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ze(n,e.label),ze(a,e.label)]);let s=await ie.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!ms(o,s)||await ie.realpath(r)!==o.realPath)throw new Error(`${e.label} source changed before move`);await ie.rename(r,i),await Promise.all([ze(n,e.label),ze(a,e.label)]);let c=await ie.lstat(i);if(!c.isDirectory()||c.isSymbolicLink()||!ms(o,c)||!Ot(n[0].realPath,await ie.realpath(i)))throw new Error(`${e.label} source identity changed while moving`);try{throw await ie.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Zn(e){let t=await Te({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await GN(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await ie.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await Te({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let r=await Te({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}var Yt=_(()=>{"use strict";Oe();Ir()});import{promises as Nl}from"fs";import Hr from"path";import{TextDecoder as vq}from"util";function bl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function kl(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function gs(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ug(e,t){if(typeof e!="string"||e.length===0||Hr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ff(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function WE(e,t){if(ug(e,t),e.includes("\\")||e!==Hr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function Rq(e,t){let r=bl(e,`transaction operations[${t}]`);if(kl(r,wq,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ug(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ug(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Vf(e){let t=bl(e,"Native Archive transaction journal");if(kl(t,yq,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!GE.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!gs(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ff(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=bl(s,`Archive transaction operations[${c}]`);if(kl(l,Nq,`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`);WE(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&WE(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Ff(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(Ff(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`);Ff(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.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 r.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(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function hg(e){let t=bl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Vf(t);if(kl(t,gq,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!GE.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Hr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Hr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!gs(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(Rq),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function XE(e,t){let r=bl(e,`Native transaction event at line ${t}`);if(kl(r,bq,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!gs(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!UE.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let i=r.type==="operation-started"||r.type==="operation-completed";if(i&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!i&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function Pq(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let i=0;i<e.length;i+=1){let n=t[i],a=e[i];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let r=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[i,n,a,o]of r){if(e.length<=i)continue;let s=e.slice(i,Math.min(i+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!gs(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||gs(e)}function vs(e,t){return e.length<t.length&&t.startsWith(e)}function Cq(e){let t='","operationId":"';if(vs(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf('"');if(i===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let n=r.slice(0,i);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?vs(r.slice(i),'"}'):!1}function xq(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>KE)return!1;let r=`{"sequence":${t},"timestamp":"`;if(vs(e,r))return!0;if(!e.startsWith(r))return!1;let i=e.slice(r.length),n=i.slice(0,Math.min(24,i.length));if(!Pq(n))return!1;if(i.length<24)return!0;if(!gs(n))return!1;let a='","type":"',o=i.slice(24);if(vs(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of UE){if(vs(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(Cq(l))return!0}else if(vs(l,'"}'))return!0}return!1}function Aq(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>KE)throw new Error(`Native transaction event at line ${t} is too large`);return XE(JSON.parse(e),t)}function _q(e){let t=e.split(`
|
|
180
180
|
`),r=t.at(-1)==="";if(r&&t.pop(),t.length>Mf)throw new Error(`Native transaction event log exceeds ${Mf} events`);let i=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!r&&n===t.length-1;try{i.push(Aq(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&xq(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return i}function QE(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
181
181
|
`)}
|
|
182
|
-
`}function Iq(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Hr.join(e.transactionsDir,t)}function Wf(e,t){let r=Iq(e,t);return{directory:r,journal:Hr.join(r,"transaction.json"),events:Hr.join(r,"events.jsonl"),staged:Hr.join(r,"staged"),backups:Hr.join(r,"backups")}}async function Ci(e,t){let r=Wf(e,t);return await Promise.all(Object.values(r).map(i=>j(e.runtimeDir,i))),r}function Tq(e,t){if(t.length===0||Hr.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let r="runtime/",i=t==="runtime"||t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":i?t.slice(r.length):t,o=Hr.resolve(n,...a.split(/[\\/]/u));if(!q(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function ea(e,t){let r=Tq(e,t);return j(F(e,r),r)}async function ao(e){try{return await Nl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pg(e,t,r={}){let i=await Ci(e,t);try{await Nl.lstat(i.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await Ie({root:e.runtimeDir,file:i.events,maxBytes:Sq,label:`Native transaction event log ${t}`,hooks:r.hooks}),a;try{a=YE.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=_q(a),s=QE(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function zE(e,t,r){let i=await pg(e,t);if(i.exists!==r.exists||i.hash!==r.hash||i.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Dr(e,t,r,i){let n=await Ci(e,t),a=await pg(e,t),o=a.events.find(c=>c.type===r&&c.operationId===i);if(o)return a.needsRepair&&await xe(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>zE(e,t,a)}),o;if(a.events.length>=Mf)throw new Error(`Native transaction event log ${t} exceeds ${Mf} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:r,...i?{operationId:i}:{}};return XE(s,s.sequence),await Nl.mkdir(n.directory,{recursive:!0}),await xe(n.events,QE([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>zE(e,t,a)}),s}async function mg(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=hg(t);let r=await Ci(e,t.id);await Nl.mkdir(r.staged,{recursive:!0}),await Nl.mkdir(r.backups,{recursive:!0}),await fe(r.journal,t,{containedRoot:e.runtimeDir}),await Dr(e,t.id,"prepared")}async function ur(e,t,r={}){let i=await Ci(e,t),n=await Ie({root:e.runtimeDir,file:i.journal,maxBytes:kq,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(YE.decode(n.bytes)),o=hg(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function ta(e,t,r={}){return(await pg(e,t,r)).events}async function Lf(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=hg({...t,status:r});return await fe((await Ci(e,t.id)).journal,i,{containedRoot:e.runtimeDir}),i}async function dg(e,t,r){try{return await Ie({root:F(e,t),file:t,maxBytes:fg,label:r})}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vg(e,t,r,i){let n=await dg(e,t,`${i} source`);if(!n)throw new Error(`${i} source does not exist`);let a=await dg(e,r,`${i} target`);await Pi({root:F(e,r),directory:Hr.dirname(r),label:`${i} target parent`}),await Zn({sourceRoot:F(e,t),source:t,targetRoot:F(e,r),target:r,maxBytes:fg,label:i,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function ZE(e,t,r){let i=await dg(e,t,r);i&&await qf({root:F(e,t),file:t,maxBytes:fg,expectedHash:i.hash,expectedSize:i.size,label:r})}async function JE(e,t){if(!t.backup)return;let r=await ea(e,t.target),i=await ea(e,t.backup);!await ao(r)||await ao(i)||await vg(e,r,i,`Legacy Native transaction backup ${t.id}`)}async function jq(e,t){let r=await ea(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await JE(e,t),await vg(e,await ea(e,t.staged),r,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await JE(e,t),await ZE(e,r,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let i=await ea(e,t.source),[n,a]=await Promise.all([ao(i),ao(r)]);if(!n&&a){await(await lr({root:F(e,r),directory:r,label:`Legacy Native transaction move target ${t.id}`,maxEntries:Eq})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await lg({root:F(e,i),source:i,target:r,label:`Legacy Native transaction move ${t.id}`})}async function eR(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=t.status==="prepared"?await Lf(e,t,"applying"):t,n=await ta(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of i.operations)a.has(s.id)||(await Dr(e,i.id,"operation-started",s.id),await jq(e,s),await Dr(e,i.id,"operation-completed",s.id),o+=1,await r?.afterOperation?.(s,o));return i=await ur(e,i.id),i}async function $q(e,t){let r=await ea(e,t.target),i=t.backup?await ea(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await ea(e,t.source);if(await ao(r)){if(await ao(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await lg({root:F(e,r),source:r,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}i&&await ao(i)?await vg(e,i,r,`Legacy Native transaction rollback restore ${t.id}`):await ZE(e,r,`Legacy Native transaction rollback remove ${t.id}`)}async function zf(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=await ta(e,t.id);if(r.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let i=await Lf(e,t,"rolling-back");await Dr(e,i.id,"rollback-started");let n=new Set(r.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...i.operations].reverse())n.has(a.id)&&await $q(e,a);return await Dr(e,i.id,"rollback-completed"),i=await Lf(e,i,"rolled-back"),i}async function ws(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Dr(e,t.id,r),r==="commit"?Lf(e,t,"committed"):t}var gq,wq,yq,Nq,bq,GE,UE,kq,Sq,KE,Mf,fg,Eq,YE,oo=_(()=>{"use strict";$e();Q();Yt();gq=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),wq=new Set(["id","type","source","target","staged","backup"]),yq=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Nq=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),bq=new Set(["sequence","timestamp","type","operationId"]),GE=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),UE=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),kq=256*1024,Sq=1024*1024,KE=16*1024,Mf=1024,fg=64*1024*1024,Eq=2e4,YE=new vq("utf-8",{fatal:!0})});import{promises as Oq}from"fs";import Hq from"path";async function Dq(e,t,r){let i;try{i=await Oq.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await ur(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(io(n.name))try{let a=await yl(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(FE(a))return!0}catch{return!0}return!1}async function Bq(e,t){let r=Date.now()+5e3,i=Hq.join(e.locksDir,"root-move.lock");for(;;)try{return await Ui(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ul(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function $(e,t,r,i){let n=await Bq(e,t);try{if(await cs(e.projectRoot),await Dq(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ki(n)}}var it=_(()=>{"use strict";tt();Qa();no();oo()});function tR(e){return Number.isSafeInteger(e)&&e>=1}async function rR(e){if(!tR(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!tR(t.revision))throw new Error("Native current revision must be a positive integer");let r=e.equals??((i,n)=>JSON.stringify(i)===JSON.stringify(n));if(t.revision===e.next.revision&&r(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}var iR=_(()=>{"use strict"});import{createHash as nR}from"crypto";import{createReadStream as qq}from"fs";async function Br(e){let t=nR("sha256");for await(let r of qq(e))t.update(r);return t.digest("hex")}function G(e){return nR("sha256").update(e).digest("hex")}var qr=_(()=>{"use strict"});import{createHash as Yf}from"crypto";import{spawn as hR}from"node:child_process";import{promises as He}from"fs";import Z from"path";function mR(e){let t=e.deadlineMs??nF;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function oi(e){return Math.max(0,e.deadlineAt-Date.now())}function U(e){return oi(e)>=1}function gg(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function bs(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function cF(e){let t={...sF,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function lF(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Z.win32.isAbsolute(i)?Z.win32.resolve(i):"C:\\Windows",a=Z.win32.join(n,"System32","taskkill.exe");if(!Z.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=hR(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),aF),u.unref()}catch{d(!1)}});for(let s=0;s<oF;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Eg(e,t,r,i){let n=oi(e);if(n<1)throw gg();let a=e.gitProcess,o=hR(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=lF(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?gg(v.error):gg()}return{code:p,spawnError:s}});return{child:o,completion:f}}function vR(e){let t={...Sg,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Gf(e,t,r,i=Ng){let{child:n,completion:a}=Eg(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,i-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>i&&(u=!0)}),n.stderr.on("data",p=>{if(c>=Ss)return;let v=Ss-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function wg(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function El(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Eg(e,t,r,i.stdin!==void 0),c=[],l=Yf("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,g=!1,w=!1,S=N=>{let y=0;for(;y<N.byteLength;){let E=N.indexOf(0,y),P=E<0?N.byteLength:E,b=N.subarray(y,P);if(!m&&b.byteLength>0&&(h.byteLength+b.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),m=!0,g=!0):h=Buffer.concat([h,b])),E<0)break;v+=1,h.byteLength===0&&!m&&(w=!0);let k=h.byteLength+1;!m&&v<=i.maxRecords&&p+k<=i.maxBytes?(c.push(h),p+=k):g=!0,h=Buffer.alloc(0),m=!1,y=E+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>i.maxBytes&&(g=!0);let y=i.outputChunkBytes;if(y===void 0){S(N);return}for(let E=0;E<N.byteLength;E+=y)S(N.subarray(E,Math.min(N.byteLength,E+y)))}),o.stderr.on("data",N=>{if(d>=Ss)return;let y=Ss-d,E=Buffer.from(N).subarray(0,y);u.push(E),d+=E.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:y})=>{let E=i.acceptedExitCodes??[0];if(N!==null&&E.includes(N)&&y===null&&!w&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${y?`: ${y.message}`:w||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function Uf(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function uF(e,t,r){if(r.length===0)return new Set;let i=await El(e,t,["check-ignore","--no-index","-z","--stdin"],{...Sg,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=Uf(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function dF(e,t,r){let{child:i,completion:n}=Eg(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=Ss)return;let d=Ss-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function ks(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||Z.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||Z.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function fF(e,t){return e.map(r=>{let i=ks(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function hF(e){let t=Z.resolve(e);for(;;){try{return await He.lstat(Z.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=Z.dirname(t);if(r===t)return!1;t=r}}async function gR(e,t,r,i={}){let n=Z.resolve(t.projectRoot),a=Z.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=Z.relative(n,Z.resolve(f)).replaceAll("\\","/"),v=ks(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},l=await El(e,n,["ls-files","--stage","-z",...s],c);await i.afterStageBefore?.();let u=await El(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await i.afterCombined?.();let d=await El(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function wR(e){return{stageBefore:wg(e.stagedBefore),combined:wg(e.combined),stageAfter:wg(e.stagedAfter)}}async function yR(e,t,r=Sg,i={}){let n=Z.resolve(t.projectRoot);if(!await hF(n))return null;let a;try{a=await Gf(e,n,["rev-parse","--is-inside-work-tree"])}catch(w){throw bs(w)?w:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:w})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await gR(e,t,r,i)}catch(w){throw bs(w)?w:new Error("Native Git snapshot provider failed after repository detection",{cause:w})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=w=>{for(let S of w){let N=Uf(S),y=N.indexOf(" ");if(y<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let E=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,y))?.groups;if(!E)throw new Error("Native Git snapshot provider returned a malformed staged header");let P=ks(N.slice(y+1));if(P===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(P),E.stage==="0"&&d.set(P,E.objectId),E.mode==="160000"&&E.stage==="0"&&f.add(P)}};p(s.records),p(l.records);let v=c.records.map(Uf),h=fF(v,"combined"),m=new Set(h.filter(w=>!u.has(w))),g=new Set(h.filter((w,S)=>!u.has(w)&&v[S].endsWith("/")));for(let w of f)g.delete(w);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:wR(o)}}function ia(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function aR(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function pF(e,t){return!ia(e.stageBefore,e.stageAfter)||!ia(e.stageAfter,t.stageBefore)||!ia(e.combined,t.combined)||!ia(t.stageBefore,t.stageAfter)}async function NR(e,t,r,i,n){let a;try{a=await gR(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw bs(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=i.initialFence,s=wR(a),c=aR(o)||aR(s),l=pF(o,s);c&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.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)&&(i.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
|
|
183
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}function vF(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function oR(e){let t=Z.resolve(e.paths.projectRoot),r=Z.resolve(e.paths.nativeRoot),i=Z.resolve(e.paths.runtimeDir),n=Z.resolve(e.paths.configFile),a=Z.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>
|
|
182
|
+
`}function Iq(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Hr.join(e.transactionsDir,t)}function Wf(e,t){let r=Iq(e,t);return{directory:r,journal:Hr.join(r,"transaction.json"),events:Hr.join(r,"events.jsonl"),staged:Hr.join(r,"staged"),backups:Hr.join(r,"backups")}}async function xi(e,t){let r=Wf(e,t);return await Promise.all(Object.values(r).map(i=>j(e.runtimeDir,i))),r}function Tq(e,t){if(t.length===0||Hr.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let r="runtime/",i=t==="runtime"||t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":i?t.slice(r.length):t,o=Hr.resolve(n,...a.split(/[\\/]/u));if(!q(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function ea(e,t){let r=Tq(e,t);return j(F(e,r),r)}async function ao(e){try{return await Nl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function pg(e,t,r={}){let i=await xi(e,t);try{await Nl.lstat(i.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await Te({root:e.runtimeDir,file:i.events,maxBytes:Sq,label:`Native transaction event log ${t}`,hooks:r.hooks}),a;try{a=YE.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=_q(a),s=QE(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function zE(e,t,r){let i=await pg(e,t);if(i.exists!==r.exists||i.hash!==r.hash||i.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Dr(e,t,r,i){let n=await xi(e,t),a=await pg(e,t),o=a.events.find(c=>c.type===r&&c.operationId===i);if(o)return a.needsRepair&&await xe(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>zE(e,t,a)}),o;if(a.events.length>=Mf)throw new Error(`Native transaction event log ${t} exceeds ${Mf} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:r,...i?{operationId:i}:{}};return XE(s,s.sequence),await Nl.mkdir(n.directory,{recursive:!0}),await xe(n.events,QE([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>zE(e,t,a)}),s}async function mg(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=hg(t);let r=await xi(e,t.id);await Nl.mkdir(r.staged,{recursive:!0}),await Nl.mkdir(r.backups,{recursive:!0}),await fe(r.journal,t,{containedRoot:e.runtimeDir}),await Dr(e,t.id,"prepared")}async function ur(e,t,r={}){let i=await xi(e,t),n=await Te({root:e.runtimeDir,file:i.journal,maxBytes:kq,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(YE.decode(n.bytes)),o=hg(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function ta(e,t,r={}){return(await pg(e,t,r)).events}async function Lf(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=hg({...t,status:r});return await fe((await xi(e,t.id)).journal,i,{containedRoot:e.runtimeDir}),i}async function dg(e,t,r){try{return await Te({root:F(e,t),file:t,maxBytes:fg,label:r})}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vg(e,t,r,i){let n=await dg(e,t,`${i} source`);if(!n)throw new Error(`${i} source does not exist`);let a=await dg(e,r,`${i} target`);await Ci({root:F(e,r),directory:Hr.dirname(r),label:`${i} target parent`}),await Zn({sourceRoot:F(e,t),source:t,targetRoot:F(e,r),target:r,maxBytes:fg,label:i,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function ZE(e,t,r){let i=await dg(e,t,r);i&&await qf({root:F(e,t),file:t,maxBytes:fg,expectedHash:i.hash,expectedSize:i.size,label:r})}async function JE(e,t){if(!t.backup)return;let r=await ea(e,t.target),i=await ea(e,t.backup);!await ao(r)||await ao(i)||await vg(e,r,i,`Legacy Native transaction backup ${t.id}`)}async function jq(e,t){let r=await ea(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await JE(e,t),await vg(e,await ea(e,t.staged),r,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await JE(e,t),await ZE(e,r,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let i=await ea(e,t.source),[n,a]=await Promise.all([ao(i),ao(r)]);if(!n&&a){await(await lr({root:F(e,r),directory:r,label:`Legacy Native transaction move target ${t.id}`,maxEntries:Eq})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await lg({root:F(e,i),source:i,target:r,label:`Legacy Native transaction move ${t.id}`})}async function eR(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=t.status==="prepared"?await Lf(e,t,"applying"):t,n=await ta(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of i.operations)a.has(s.id)||(await Dr(e,i.id,"operation-started",s.id),await jq(e,s),await Dr(e,i.id,"operation-completed",s.id),o+=1,await r?.afterOperation?.(s,o));return i=await ur(e,i.id),i}async function $q(e,t){let r=await ea(e,t.target),i=t.backup?await ea(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await ea(e,t.source);if(await ao(r)){if(await ao(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await lg({root:F(e,r),source:r,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}i&&await ao(i)?await vg(e,i,r,`Legacy Native transaction rollback restore ${t.id}`):await ZE(e,r,`Legacy Native transaction rollback remove ${t.id}`)}async function zf(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=await ta(e,t.id);if(r.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let i=await Lf(e,t,"rolling-back");await Dr(e,i.id,"rollback-started");let n=new Set(r.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...i.operations].reverse())n.has(a.id)&&await $q(e,a);return await Dr(e,i.id,"rollback-completed"),i=await Lf(e,i,"rolled-back"),i}async function ws(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Dr(e,t.id,r),r==="commit"?Lf(e,t,"committed"):t}var gq,wq,yq,Nq,bq,GE,UE,kq,Sq,KE,Mf,fg,Eq,YE,oo=_(()=>{"use strict";Oe();Q();Yt();gq=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),wq=new Set(["id","type","source","target","staged","backup"]),yq=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Nq=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),bq=new Set(["sequence","timestamp","type","operationId"]),GE=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),UE=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),kq=256*1024,Sq=1024*1024,KE=16*1024,Mf=1024,fg=64*1024*1024,Eq=2e4,YE=new vq("utf-8",{fatal:!0})});import{promises as Oq}from"fs";import Hq from"path";async function Dq(e,t,r){let i;try{i=await Oq.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await ur(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(io(n.name))try{let a=await yl(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(FE(a))return!0}catch{return!0}return!1}async function Bq(e,t){let r=Date.now()+5e3,i=Hq.join(e.locksDir,"root-move.lock");for(;;)try{return await Ki(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ul(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function $(e,t,r,i){let n=await Bq(e,t);try{if(await cs(e.projectRoot),await Dq(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Yi(n)}}var it=_(()=>{"use strict";tt();Qa();no();oo()});function tR(e){return Number.isSafeInteger(e)&&e>=1}async function rR(e){if(!tR(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!tR(t.revision))throw new Error("Native current revision must be a positive integer");let r=e.equals??((i,n)=>JSON.stringify(i)===JSON.stringify(n));if(t.revision===e.next.revision&&r(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}var iR=_(()=>{"use strict"});import{createHash as nR}from"crypto";import{createReadStream as qq}from"fs";async function Br(e){let t=nR("sha256");for await(let r of qq(e))t.update(r);return t.digest("hex")}function G(e){return nR("sha256").update(e).digest("hex")}var qr=_(()=>{"use strict"});import{createHash as Yf}from"crypto";import{spawn as hR}from"node:child_process";import{promises as De}from"fs";import Z from"path";function mR(e){let t=e.deadlineMs??nF;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function si(e){return Math.max(0,e.deadlineAt-Date.now())}function K(e){return si(e)>=1}function gg(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function bs(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function cF(e){let t={...sF,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function lF(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&Z.win32.isAbsolute(i)?Z.win32.resolve(i):"C:\\Windows",a=Z.win32.join(n,"System32","taskkill.exe");if(!Z.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,p=!1)=>{c||(c=!0,u&&clearTimeout(u),p&&l?.kill("SIGKILL"),s(f))};try{l=hR(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),aF),u.unref()}catch{d(!1)}});for(let s=0;s<oF;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Eg(e,t,r,i){let n=si(e);if(n<1)throw gg();let a=e.gitProcess,o=hR(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",p=>{s=p});let u=new Promise(p=>{o.once("close",p)}),d=setTimeout(()=>{c=!0,l=lF(o,a).then(()=>({error:null}),p=>({error:p}))},n);d.unref();let f=u.then(async p=>{if(clearTimeout(d),c){let v=await l;throw v?.error?gg(v.error):gg()}return{code:p,spawnError:s}});return{child:o,completion:f}}function vR(e){let t={...Sg,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Gf(e,t,r,i=Ng){let{child:n,completion:a}=Eg(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",p=>{let v=Math.max(0,i-l);v>0&&o.push(Buffer.from(p).subarray(0,v)),l+=p.byteLength,l>i&&(u=!0)}),n.stderr.on("data",p=>{if(c>=Ss)return;let v=Ss-c,h=Buffer.from(p).subarray(0,v);s.push(h),c+=h.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function wg(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function El(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Eg(e,t,r,i.stdin!==void 0),c=[],l=Yf("sha256"),u=[],d=0,f=0,p=0,v=0,h=Buffer.alloc(0),m=!1,g=!1,w=!1,S=N=>{let y=0;for(;y<N.byteLength;){let E=N.indexOf(0,y),P=E<0?N.byteLength:E,b=N.subarray(y,P);if(!m&&b.byteLength>0&&(h.byteLength+b.byteLength>i.maxRecordBytes?(h=Buffer.alloc(0),m=!0,g=!0):h=Buffer.concat([h,b])),E<0)break;v+=1,h.byteLength===0&&!m&&(w=!0);let k=h.byteLength+1;!m&&v<=i.maxRecords&&p+k<=i.maxBytes?(c.push(h),p+=k):g=!0,h=Buffer.alloc(0),m=!1,y=E+1}};o.stdout.on("data",N=>{l.update(N),f+=N.byteLength,f>i.maxBytes&&(g=!0);let y=i.outputChunkBytes;if(y===void 0){S(N);return}for(let E=0;E<N.byteLength;E+=y)S(N.subarray(E,Math.min(N.byteLength,E+y)))}),o.stderr.on("data",N=>{if(d>=Ss)return;let y=Ss-d,E=Buffer.from(N).subarray(0,y);u.push(E),d+=E.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:N,spawnError:y})=>{let E=i.acceptedExitCodes??[0];if(N!==null&&E.includes(N)&&y===null&&!w&&h.byteLength===0&&!m){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${y?`: ${y.message}`:w||h.byteLength>0||m?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function Uf(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function uF(e,t,r){if(r.length===0)return new Set;let i=await El(e,t,["check-ignore","--no-index","-z","--stdin"],{...Sg,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=Uf(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function dF(e,t,r){let{child:i,completion:n}=Eg(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=Ss)return;let d=Ss-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function ks(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||Z.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||Z.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function fF(e,t){return e.map(r=>{let i=ks(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function hF(e){let t=Z.resolve(e);for(;;){try{return await De.lstat(Z.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=Z.dirname(t);if(r===t)return!1;t=r}}async function gR(e,t,r,i={}){let n=Z.resolve(t.projectRoot),a=Z.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let p=Z.relative(n,Z.resolve(f)).replaceAll("\\","/"),v=ks(p);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},l=await El(e,n,["ls-files","--stage","-z",...s],c);await i.afterStageBefore?.();let u=await El(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await i.afterCombined?.();let d=await El(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function wR(e){return{stageBefore:wg(e.stagedBefore),combined:wg(e.combined),stageAfter:wg(e.stagedAfter)}}async function yR(e,t,r=Sg,i={}){let n=Z.resolve(t.projectRoot);if(!await hF(n))return null;let a;try{a=await Gf(e,n,["rev-parse","--is-inside-work-tree"])}catch(w){throw bs(w)?w:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:w})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await gR(e,t,r,i)}catch(w){throw bs(w)?w:new Error("Native Git snapshot provider failed after repository detection",{cause:w})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,p=w=>{for(let S of w){let N=Uf(S),y=N.indexOf(" ");if(y<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let E=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(N.slice(0,y))?.groups;if(!E)throw new Error("Native Git snapshot provider returned a malformed staged header");let P=ks(N.slice(y+1));if(P===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(P),E.stage==="0"&&d.set(P,E.objectId),E.mode==="160000"&&E.stage==="0"&&f.add(P)}};p(s.records),p(l.records);let v=c.records.map(Uf),h=fF(v,"combined"),m=new Set(h.filter(w=>!u.has(w))),g=new Set(h.filter((w,S)=>!u.has(w)&&v[S].endsWith("/")));for(let w of f)g.delete(w);return{tracked:u,trackedObjectIds:d,untracked:m,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:wR(o)}}function ia(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function aR(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function pF(e,t){return!ia(e.stageBefore,e.stageAfter)||!ia(e.stageAfter,t.stageBefore)||!ia(e.combined,t.combined)||!ia(t.stageBefore,t.stageAfter)}async function NR(e,t,r,i,n){let a;try{a=await gR(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw bs(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=i.initialFence,s=wR(a),c=aR(o)||aR(s),l=pF(o,s);c&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.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)&&(i.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
|
|
183
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}function vF(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function oR(e){let t=Z.resolve(e.paths.projectRoot),r=Z.resolve(e.paths.nativeRoot),i=Z.resolve(e.paths.runtimeDir),n=Z.resolve(e.paths.configFile),a=Z.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,p=!1,v=!1,h=!1,m=()=>si(e.execution)>=1?!0:(p=!0,h=!0,!1),g=N=>{let y=Buffer.from(`${N.type}\0${N.path}`,"utf8"),E=Yf("sha256").update("comet.native.physical-selection-record.v1\0").update(y).digest();for(let P=0;P<c.length;P+=1)c[P]^=E[P];if(l=l+BigInt(`0x${E.toString("hex")}`)&mF,d+=1,f+=y.byteLength,Buffer.byteLength(N.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){p=!0,h=!0;return}o.push(N)},w=async N=>{if(h||!m())return;let y;try{y=await De.opendir(N)}catch(R){if(!m())return;if(!at(R)&&!nt(R)||N===t&&at(R))throw R;v||=nt(R),p||=at(R),h=!0;return}if(!m()){try{await y.close()}catch(R){if(R.code!=="ERR_DIR_CLOSED")throw R}return}let E=!1,P;try{for(;!h&&m();){let R;try{R=await y.read()}catch(ce){if(!m())break;if(!at(ce)&&!nt(ce)||N===t&&at(ce))throw ce;v||=nt(ce),p||=at(ce),h=!0;break}if(!m()||R===null)break;if(u+=1,u>e.limits.maxNodes){p=!0,h=!0;break}let I=Z.join(N,R.name),C=wF(t,I);if(I===n||I===a||ci(r,I)||ci(i,I)||e.denylist.some(ce=>ci(ce,I))||Ni(C)!==null)continue;if(!m())break;let Ne;try{Ne=await De.lstat(I)}catch(ce){if(!m())break;if(!at(ce)&&!nt(ce))throw ce;if(v=!0,g({path:C,type:"other"}),s.push({path:C,size:null,type:"file",reason:at(ce)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(C),h||!m())break;continue}if(!m())break;let oe=vF(Ne);if(oe==="directory"){if(kF(e.policy,C))continue;if(!m())break;let ce;try{ce=await De.realpath(I)}catch(Ue){if(!m())break;if(!at(Ue)&&!nt(Ue))throw Ue;if(v=!0,g({path:C,type:oe}),s.push({path:C,size:null,type:"directory",reason:at(Ue)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(C),h||!m())break;continue}if(!m())break;if(!q(e.physicalProjectRoot,ce)||ci(e.physicalNativeRoot,ce))continue;if(g({path:C,type:oe}),await e.hooks?.afterNode?.(C),!m()||(await w(I),h))break;continue}if(g({path:C,type:oe}),await e.hooks?.afterNode?.(C),!m()||h)break}}catch(R){E=!0,P=R}let b;try{await y.close()}catch(R){b=R}let k=m();if(E)throw P;if(k&&b!==void 0&&b.code!=="ERR_DIR_CLOSED")throw b};await w(t),m(),p?(o.length=0,d=0,f=0):(o.sort((N,y)=>N.path.localeCompare(y.path,"en")),s.sort((N,y)=>N.path.localeCompare(y.path,"en")));let S=p?G(`comet.native.physical-selection-incomplete.v1
|
|
184
184
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):G(`comet.native.physical-selection.v1
|
|
185
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function bR(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function gF(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!bR(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function kR(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function sR(e,t){let i=(await Gf(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!pR.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return G(`gitlink:${i}`)}async function cR(e,t){let r=await sR(e,t),i=await dF(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await sR(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Sl(e,t){if(
|
|
185
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:S,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:p,unstable:v}}}function bR(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function gF(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!bR(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function kR(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function sR(e,t){let i=(await Gf(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!pR.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return G(`gitlink:${i}`)}async function cR(e,t){let r=await sR(e,t),i=await dF(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await sR(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Sl(e,t){if(Ni(t)!==null)return!1;let r=Z.resolve(e.projectRoot,...t.split("/"));return!ci(Z.resolve(e.nativeRoot),r)&&!ci(Z.resolve(e.runtimeDir),r)}function Rg(e,t={}){let r=Zi(e),i=t.maxRecordedPaths??20;if(!Number.isSafeInteger(i)||i<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=r.omitted.slice(0,i).map(a=>a.path);return{complete:r.complete,omittedCount:r.omittedCount,recordedOmissionCount:r.omitted.length,overflowCount:r.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<r.omittedCount}}function wF(e,t){return Z.relative(e,t).split(Z.sep).join("/")}function yF(e,t){return t.map(r=>Z.resolve(e,...r.split(/[\\/]/u)))}function ci(e,t){let r=Z.resolve(e),i=Z.resolve(t);return i===r||q(r,i)}function at(e){return iF.has(e.code??"")}function nt(e){return e.code==="ENOENT"}function Pg(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
186
186
|
`)}function NF(e,t){return G(`comet.native.snapshot-policy.v1
|
|
187
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function yg(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function bF(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function lR(e){let t=Nf(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?bF(n):void 0;if(a&&!a())return!1;let o=yg(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=yg(r,c,a),o===null||o.size===0)return!1}return yg(r,o,a)?.has(r.length)??!1}}function SR(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Nf(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Nf(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=NF(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(lR),excludeMatchers:r.map(lR),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function kF(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function uR(e,t,r){if(!e)return!0;let i=()=>
|
|
187
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function yg(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function bF(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function lR(e){let t=Nf(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?bF(n):void 0;if(a&&!a())return!1;let o=yg(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=yg(r,c,a),o===null||o.size===0)return!1}return yg(r,o,a)?.has(r.length)??!1}}function SR(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>Nf(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>Nf(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=NF(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(lR),excludeMatchers:r.map(lR),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function kF(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function uR(e,t,r){if(!e)return!0;let i=()=>K(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function Rl(e,t,r){let i=JSON.stringify(r);return G(`${e}
|
|
188
188
|
${Buffer.byteLength(t)}:${t}
|
|
189
|
-
${Buffer.byteLength(i)}:${i}`)}function bg(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Kf(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!bg(r))return e.splice(t,1),r}return null}function ra(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function SF(e,t,r,i){if(!U(i))return{status:"budget-exhausted"};let n;try{n=await He.open(e,"r")}catch(c){if(!U(i))return{status:"budget-exhausted"};throw c}if(!U(i))return await n.close(),{status:"budget-exhausted"};let a=Yf("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!U(i))return{status:"budget-exhausted"};let c=await n.stat();if(!U(i))return{status:"budget-exhausted"};if(!c.isFile()||!ra(r,c))return{status:"changed"};for(;;){if(!U(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!U(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!U(i))return{status:"budget-exhausted"};let d=await n.stat();return U(i)?!d.isFile()||!ra(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Fr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mr(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Ns(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ER(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Z.posix.normalize(e);if(r!==e||Z.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function EF(e,t){let r=Fr(e,`Native snapshot entry ${t}`);Mr(r,Xq,`Native snapshot entry ${t}`);let i=ER(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Xf.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:xi(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!pR.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function RF(e,t){let r=Fr(e,`Native snapshot omission ${t}`);if(Mr(r,Qq,`Native snapshot omission ${t}`),!tF.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!rF.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:ER(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:xi(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function PF(e){let t=Fr(e,"Native snapshot omission overflow");if(Mr(t,Zq,"Native snapshot omission overflow"),typeof t.hash!="string"||!Xf.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Ns(t.count,"Native snapshot omission overflow count")}}function ys(e,t){let r=Fr(e,t);if(Mr(r,Uq,t),typeof r.hash!="string"||!Xf.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=xi(r.recordCount,`${t} recordCount`),n=xi(r.storedRecordCount,`${t} storedRecordCount`),a=xi(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function dR(e){let t=Fr(e,"Native Git selection evidence");if(Mr(t,Gq,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=ys(t.stageBefore,"Native Git selection stageBefore"),i=ys(t.combined,"Native Git selection combined"),n=ys(t.stageAfter,"Native Git selection stageAfter"),a=ys(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ys(t.finalCombined,"Native Git selection finalCombined"),s=ys(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!ia(r,n)||!ia(n,a)||!ia(i,o)||!ia(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function fR(e,t){let r=Fr(e,t);if(Mr(r,Yq,t),typeof r.hash!="string"||!Xf.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=xi(r.visitedNodeCount,`${t} visitedNodeCount`),n=xi(r.recordCount,`${t} recordCount`),a=xi(r.storedRecordCount,`${t} storedRecordCount`),o=xi(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function CF(e){let t=Fr(e,"Native physical selection evidence");if(Mr(t,Kq,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=fR(t.before,"Native physical selection before"),i=fR(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!bR(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function Qi(e){let t=Fr(e,"Native content snapshot manifest");if(Mr(t,Lq,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!eF.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let E=Fr(t.capture,"Native content snapshot capture");if(Mr(E,zq,"Native content snapshot capture"),E.provider!=="git"&&E.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=E.gitSelection===void 0?void 0:dR(E.gitSelection),b=E.physicalSelection===void 0?void 0:CF(E.physicalSelection),k=null;if(E.projection!==void 0){let R=Fr(E.projection,"Native content snapshot projection");if(Mr(R,Jq,"Native content snapshot projection"),R.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");k={provider:"git",...R.selection===void 0?{}:{selection:dR(R.selection)}}}if(E.provider==="git"){if(b||k)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&k)throw new Error("Native physical-tree capture cannot combine selection and projection");r=k?{provider:"physical-tree",projection:k}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=Fr(t.limits,"Native content snapshot limits");Mr(i,Vq,"Native content snapshot limits");let n={maxFiles:Ns(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Ns(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Ns(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Ns(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Ns(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let E=Fr(t.policy,"Native snapshot policy");if(Mr(E,Wq,"Native snapshot policy"),E.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(E.include)||!Array.isArray(E.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=SR({include:E.include,exclude:E.exclude,hash:E.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(EF),s=t.omitted.map(RF),c=xi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:PF(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(E=>E.size>n.maxFileBytes)||o.reduce((E,P)=>E+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(E=>E.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>kg||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(E=>E.reason==="git-enumeration-limit"),f=s.filter(E=>E.reason==="git-selection-changed");for(let E of[...d,...f])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(E=>E.reason==="physical-enumeration-limit"),g=s.filter(E=>E.reason==="physical-selection-changed");for(let E of[...m,...g])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,S=w?.status==="overflow"||w?.status==="overflow-and-changed",N=w?.status==="changed"||w?.status==="overflow-and-changed";if(S!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let y={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Pg(y)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return y}async function Qf(e,t,r={}){let i=Qi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=Z.resolve(e.projectRoot),a=mR(r),o=vR(r.gitSelectionLimits),s=await yR(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(kR(s).filter(b=>Sl(e,b))),l=[...s.gitlinks].filter(b=>c.has(b)),u=[...s.nestedRepositories].filter(b=>Sl(e,b)),d=(b,k)=>k.some(R=>b===R||b.startsWith(`${R}/`)),f=b=>d(b,l),p=b=>d(b,u),v=[...i.entries.map(b=>b.path),...i.omitted.flatMap(b=>b.type==="directory"?[b.path,`${b.path}/`]:[b.path])].filter(b=>!c.has(b)&&!f(b)&&!p(b)),h=await uF(a,n,v),m=i.entries.filter(b=>!f(b.path)&&!p(b.path)&&Sl(e,b.path)&&(c.has(b.path)||!h.has(b.path)));await NR(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let b of l)g.push({path:b,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((b,k)=>b.path.localeCompare(k.path,"en"));let w=i.omitted.filter(b=>f(b.path)||p(b.path)||!Sl(e,b.path)?!1:h.has(b.path)?c.has(b.path)||[...c].some(k=>k.startsWith(`${b.path}/`)):!0);for(let b of g)w.some(k=>k.path===b.path&&k.reason===b.reason)||w.push(b);w.sort((b,k)=>b.path.localeCompare(k.path,"en"));let S=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??G("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,N=Rl(N,"git-selection",{source:"git-selection",...s.overflow}));let y=b=>{S+=1,N=Rl(N,"omission",b)};for(;w.length>kg;){let b=Kf(w);if(b===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");y(b)}let E=()=>({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:w.length+S===0,entries:m,omitted:w,omittedCount:w.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:S}}:{}}),P=E();for(;Pg(P)>i.limits.maxManifestBytes;){let b=Kf(w);if(b===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");y(b),P=E()}return Qi(P)}function RR(e,t){if(!Mq.test(t))throw new Error(`Invalid Native change name: ${t}`);return Z.join(V(e,t),"baseline-manifest.json")}async function Zf(e,t={}){let r={maxFiles:t.limits?.maxFiles??Jf.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Jf.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Jf.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Jf.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=SR(t.policy),n=mR({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=vR(t.gitSelectionLimits),o=cF(t.physicalSelectionLimits);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=Z.resolve(e.projectRoot),c=await He.realpath(s),l=Z.resolve(e.nativeRoot),u=await He.realpath(l),d=Z.resolve(e.runtimeDir),f=Z.resolve(e.configFile),p=Z.join(s,".comet","current-change.json"),v=yF(s,t.denylist??[]),h=[],m=[],g=new Map,w=new Map,S=0,N=0,y=G("comet.native.snapshot-omission-overflow.v1"),E=0,P=!1,b=null,k=H=>{N+=1,y=Rl(y,"omission",H)},R=H=>{if(S+=1,m.length<kg){m.push(H);return}if(bg(H)){let O=Kf(m);if(O===null)throw new Error("Native snapshot has too many required selection-integrity omissions");k(O),m.push(H);return}k(H)},I=H=>{S+=H.count,N+=H.count,y=Rl(y,"git-selection",{source:"git-selection",...H})},C=H=>{N+=1,y=Rl(y,"manifest-entry",{reason:"manifest-size",entry:H})},Ne=async(H,O)=>{h.push(H),E+=H.size,g.set(H.path,O),P||(P=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(H.path))},oe=(H,O)=>{let M=h.findIndex(je=>je.path===H);if(M<0)return;let[te]=h.splice(M,1);E-=te.size,g.delete(H),R(O)},ce=async(H,O,M,te)=>{if(!M.isFile()||M.isSymbolicLink()||!U(n))return;let je;try{je=await He.realpath(H)}catch(T){if(!U(n))return;if(!at(T)&&!nt(T))throw T;R({path:O,size:M.size,type:"file",reason:nt(T)?"changed-during-read":"unreadable"});return}if(!U(n)||!q(c,je)||si(u,je))return;if(h.length>=r.maxFiles){R({path:O,size:M.size,type:"file",reason:"file-count"});return}if(M.size>r.maxFileBytes){R({path:O,size:M.size,type:"file",reason:"file-size"});return}if(E+M.size>r.maxTotalBytes){R({path:O,size:M.size,type:"file",reason:"total-size"});return}let de,Y,Ve;try{if(de=await SF(je,M.size,M,n),de.status==="budget-exhausted"||!U(n))return;if(de.status==="changed"){R({path:O,size:null,type:"file",reason:"changed-during-read"});return}if(!U(n)||(Ve=await He.realpath(H),!U(n)))return;Y=await He.lstat(H)}catch(T){if(!U(n))return;if(!at(T)&&!nt(T))throw T;R({path:O,size:M.size,type:"file",reason:nt(T)?"changed-during-read":"unreadable"});return}if(U(n)){if(de.bytes!==M.size||Ve!==je||!ra(M,de.finalStat)||!ra(de.finalStat,Y)||!Y.isFile()||Y.isSymbolicLink()||Y.size!==M.size||Y.mtimeMs!==M.mtimeMs||Y.ctimeMs!==M.ctimeMs){R({path:O,size:Y.isFile()?Y.size:null,type:Y.isFile()?"file":"other",reason:"changed-during-read"});return}U(n)&&await Ne({path:O,hash:de.hash,size:Y.size,type:"file",...te===void 0?{}:{gitObjectId:te}},{kind:"file",target:H,realTarget:je,stat:Y})}},Ue=async(H,O,M)=>{if(!U(n))return;let te,je,de;try{if(te=await He.readlink(H,{encoding:"buffer"}),!U(n)||(de=await He.lstat(H),!U(n)))return;je=await He.readlink(H,{encoding:"buffer"})}catch(T){if(!U(n))return;if(!at(T)&&!nt(T))throw T;R({path:O,size:null,type:"other",reason:nt(T)?"changed-during-read":"unreadable"});return}if(!U(n))return;if(!de.isSymbolicLink()||!ra(M,de)||de.mtimeMs!==M.mtimeMs||de.ctimeMs!==M.ctimeMs||!te.equals(je)){R({path:O,size:null,type:"other",reason:"changed-during-read"});return}let Y=te.byteLength;if(h.length>=r.maxFiles){R({path:O,size:Y,type:"other",reason:"file-count"});return}if(Y>r.maxFileBytes){R({path:O,size:Y,type:"other",reason:"file-size"});return}if(E+Y>r.maxTotalBytes){R({path:O,size:Y,type:"other",reason:"total-size"});return}let Ve=Yf("sha256").update("symlink\0").update(te).digest("hex");U(n)&&await Ne({path:O,hash:Ve,size:Y,type:"file"},{kind:"symlink",target:H,rawTarget:te,stat:de})},Ke=async()=>{for(let[H,O]of[...g]){if(!U(n))return;if(O.kind==="file"){let Y,Ve;try{if(Y=await He.realpath(O.target),!U(n))return;Ve=await He.lstat(O.target)}catch(T){if(!U(n))return;if(!at(T)&&!nt(T))throw T;oe(H,{path:H,size:null,type:"file",reason:at(T)?"unreadable":"changed-during-read"});continue}if(!U(n))return;(Y!==O.realTarget||!Ve.isFile()||Ve.isSymbolicLink()||!ra(O.stat,Ve)||Ve.size!==O.stat.size||Ve.mtimeMs!==O.stat.mtimeMs||Ve.ctimeMs!==O.stat.ctimeMs)&&oe(H,{path:H,size:Ve.isFile()?Ve.size:null,type:Ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(O.kind==="symlink"){let Y,Ve;try{if(Y=await He.lstat(O.target),!U(n))return;Ve=await He.readlink(O.target,{encoding:"buffer"})}catch(T){if(!U(n))return;if(!at(T)&&!nt(T))throw T;oe(H,{path:H,size:null,type:"other",reason:at(T)?"unreadable":"changed-during-read"});continue}if(!U(n))return;(!Y.isSymbolicLink()||!ra(O.stat,Y)||Y.mtimeMs!==O.stat.mtimeMs||Y.ctimeMs!==O.stat.ctimeMs||!O.rawTarget.equals(Ve))&&oe(H,{path:H,size:null,type:"other",reason:"changed-during-read"});continue}let M,te;try{if(M=await He.realpath(O.target),!U(n))return;te=await He.lstat(O.target)}catch{if(!U(n))return;oe(H,{path:H,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!U(n))return;if(!(M===O.realTarget&&te.isDirectory()&&!te.isSymbolicLink()&&ra(O.stat,te)&&q(c,M)&&!si(u,M))){oe(H,{path:H,size:null,type:"directory",reason:"gitlink-changed"});continue}let de;try{if(!U(n))return;de=await cR(n,M)}catch(Y){if(bs(Y))throw Y;oe(H,{path:H,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!U(n))return;de.dirty?oe(H,{path:H,size:null,type:"directory",reason:"gitlink-dirty"}):de.hash!==O.hash&&oe(H,{path:H,size:null,type:"directory",reason:"gitlink-changed"})}for(let[H,O]of w){if(!U(n))return;try{let M=await He.lstat(O);if(!U(n))return;R({path:H,size:M.isFile()?M.size:null,type:M.isFile()?"file":M.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(M){if(!U(n))return;if(nt(M))continue;if(!at(M))throw M;R({path:H,size:null,type:"file",reason:"unreadable"})}}},jt=await yR(n,e,a,t.gitSelectionHooks);if(jt===null){let H=await oR({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let te of H.records){if(te.type!=="file"&&te.type!=="symlink"||g.has(te.path))continue;if(oi(n)<1)break;if(!uR(i,te.path,n))continue;if(oi(n)<1)break;let je=Z.resolve(s,...te.path.split("/")),de;try{de=await He.lstat(je)}catch(Y){if(!U(n))break;if(!at(Y)&&!nt(Y))throw Y;R({path:te.path,size:null,type:"file",reason:nt(Y)?"changed-during-read":"unreadable"});continue}if(oi(n)<1)break;if(te.type==="symlink"&&de.isSymbolicLink()){if(await Ue(je,te.path,de),oi(n)<1)break;continue}if(te.type!=="file"||!de.isFile()||de.isSymbolicLink()){R({path:te.path,size:de.isFile()?de.size:null,type:de.isDirectory()?"directory":de.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ce(je,te.path,de),oi(n)<1)break}oi(n)>=1&&await Ke();let O=await oR({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o}),M=gF(H.evidence,O.evidence);b=M.evidence;for(let te of[...H.omissions,...O.omissions,...M.omissions])m.some(je=>je.path===te.path&&je.reason===te.reason)||R(te)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let H=t.incrementalBaseline,O=new Map,M=!1;if(H){let T=Qi(H);for(let Fe of T.entries)Fe.gitObjectId!==void 0&&O.set(Fe.path,Fe);M=O.size>0}let te=new Set,je=!0;try{let T=await El(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(T.overflow)M=!1,je=!1,O.clear();else for(let Fe of T.records){let We=Uf(Fe),Wt=We.indexOf(" "),$t=Wt<0?null:ks(We.slice(Wt+1));if(Wt!==1||$t===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");We[0]!=="H"&&te.add($t)}}catch(T){if(bs(T))throw T;M=!1,je=!1,O.clear()}let de=new Set;try{let T=await Gf(n,s,["ls-files","--modified","-z"],Ng);for(let Fe of T.toString("utf8").split("\0")){let We=ks(Fe);We!==null&&de.add(We)}}catch{M=!1,je=!1,O.clear()}let Y=new Set,Ve=new Set;for(let T of kR(jt)){if(g.has(T)||!Sl(e,T))continue;if(oi(n)<1)break;if(!uR(i,T,n))continue;if(oi(n)<1)break;let Fe=Z.resolve(s,...T.split("/"));if(Fe===f||Fe===p||si(d,Fe)||v.some(gr=>si(gr,Fe)))continue;if(jt.gitlinks.has(T)){if(h.length>=r.maxFiles){R({path:T,size:0,type:"file",reason:"file-count"});continue}let gr,Qu;try{[gr,Qu]=await Promise.all([He.realpath(Fe),He.lstat(Fe)])}catch{R({path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Qu.isSymbolicLink()||!Qu.isDirectory()||!q(c,gr)||si(u,gr)){R({path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Lo=await cR(n,gr);if(Lo.dirty){R({path:T,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Ne({path:T,hash:Lo.hash,size:0,type:"file"},{kind:"gitlink",target:Fe,realTarget:gr,stat:Qu,hash:Lo.hash})}catch(Lo){if(bs(Lo))throw Lo;R({path:T,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let We;try{We=await He.lstat(Fe)}catch(gr){if(nt(gr)&&jt.tracked.has(T)){w.set(T,Fe);continue}if(!at(gr)&&!nt(gr))throw gr;R({path:T,size:null,type:"file",reason:nt(gr)?"changed-during-read":"unreadable"});continue}if(We.isSymbolicLink()){await Ue(Fe,T,We);continue}if(!We.isFile()){jt.nestedRepositories.has(T)||R({path:T,size:null,type:"other",reason:"changed-during-read"});continue}let Wt=jt.trackedObjectIds.get(T),$t=Wt?O.get(T):void 0;if(M&&$t?.gitObjectId!==void 0&&$t.gitObjectId===Wt&&!te.has(T)&&!de.has(T)){if(h.length>=r.maxFiles){R({path:T,size:$t.size,type:"file",reason:"file-count"});continue}if($t.size>r.maxFileBytes){R({path:T,size:$t.size,type:"file",reason:"file-size"});continue}if(E+$t.size>r.maxTotalBytes){R({path:T,size:$t.size,type:"file",reason:"total-size"});continue}h.push({...$t}),E+=$t.size,Y.add(T);continue}let WN=je&&!te.has(T)&&!de.has(T)?Wt:void 0;await ce(Fe,T,We,WN),WN!==void 0&&Ve.add(T)}if(await Ke(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await NR(n,e,a,jt,t.gitSelectionHooks?.outputChunkBytes),Y.size>0||M&&Ve.size>0){let T=await Gf(n,s,["ls-files","--modified","-z"],Ng),Fe=new Set;for(let We of T.toString("utf8").split("\0")){let Wt=ks(We);Wt!==null&&Fe.add(Wt)}for(let We of Y){if(!Fe.has(We))continue;let Wt=h.find($t=>$t.path===We);oe(We,{path:We,size:Wt?.size??null,type:"file",reason:"changed-during-read"})}for(let We of Ve){if(!Fe.has(We))continue;let Wt=h.find($t=>$t.path===We);Wt&&delete Wt.gitObjectId}}for(let T of jt.omissions)R(T);jt.overflow&&I(jt.overflow)}h.sort((H,O)=>H.path.localeCompare(O.path,"en")),m.sort((H,O)=>H.path.localeCompare(O.path,"en"));let aj=jt===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...jt.evidence?{gitSelection:jt.evidence}:{}},VN=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:aj,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:m,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${y}`,hash:y,count:N}}:{}}),Lp=VN();for(;Pg(Lp)>r.maxManifestBytes;){if(m.filter(O=>!bg(O)).length>0){let O=Math.max(1,Math.ceil(m.length/4));for(let M=0;M<O;M+=1){let te=Kf(m);if(te===null)break;k(te)}}else if(h.length>0){let O=Math.max(1,Math.ceil(h.length/4));for(let M of h.splice(-O))S+=1,C(M)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Lp=VN()}return Lp}async function Es(e,t,r={}){let n=(await X(e.projectRoot))?.native.snapshot??Wv;return Zf(e,{...r,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Cg(e,t,r){let i=RR(e,t);await j(F(e,i),i),await fe(i,Qi(r))}async function Rs(e,t){let r=RR(e,t),i=F(e,r);await j(i,r);try{let n=await Bf({root:i,file:r,maxBytes:Fq,label:"Native baseline snapshot manifest"});return Qi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var Jf,kg,Fq,Mq,Lq,Vq,Wq,zq,Jq,Gq,Uq,Kq,Yq,Xq,Qq,Zq,eF,tF,rF,Xf,pR,iF,Ss,Ng,nF,aF,oF,Sg,sF,mF,na=_(()=>{"use strict";$e();tt();qr();Ir();Q();Yt();Nc();Jf={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},kg=1e3,Fq=8*1024*1024,Mq=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lq=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Vq=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Wq=new Set(["schema","include","exclude","hash"]),zq=new Set(["provider","gitSelection","physicalSelection","projection"]),Jq=new Set(["provider","selection"]),Gq=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Uq=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Kq=new Set(["schema","status","before","after"]),Yq=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Xq=new Set(["path","hash","size","type","gitObjectId"]),Qq=new Set(["path","size","type","reason"]),Zq=new Set(["ref","hash","count"]),eF=new Set(["change-created","legacy-migration","explicit"]),tF=new Set(["file","directory","other"]),rF=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"]),Xf=/^[a-f0-9]{64}$/u,pR=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,iF=new Set(["EACCES","EPERM"]),Ss=64*1024,Ng=64*1024,nF=6e4,aF=1e3,oF=2,Sg={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},sF={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};mF=(1n<<256n)-1n});var kr,Ps=_(()=>{"use strict";kr=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"})});var eh=_(()=>{"use strict"});var PR=_(()=>{"use strict"});var xg=_(()=>{"use strict";eh()});var CR=_(()=>{"use strict";eh();xg()});var jF,xR=_(()=>{"use strict";jF=Ha(Mn(),1);as();Vn();Ga()});import{promises as $F}from"node:fs";import OF from"node:path";function HF(e){return e.includes(`\r
|
|
189
|
+
${Buffer.byteLength(i)}:${i}`)}function bg(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function Kf(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!bg(r))return e.splice(t,1),r}return null}function ra(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function SF(e,t,r,i){if(!K(i))return{status:"budget-exhausted"};let n;try{n=await De.open(e,"r")}catch(c){if(!K(i))return{status:"budget-exhausted"};throw c}if(!K(i))return await n.close(),{status:"budget-exhausted"};let a=Yf("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!K(i))return{status:"budget-exhausted"};let c=await n.stat();if(!K(i))return{status:"budget-exhausted"};if(!c.isFile()||!ra(r,c))return{status:"changed"};for(;;){if(!K(i))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!K(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!K(i))return{status:"budget-exhausted"};let d=await n.stat();return K(i)?!d.isFile()||!ra(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Fr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mr(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Ns(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ai(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function ER(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Z.posix.normalize(e);if(r!==e||Z.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function EF(e,t){let r=Fr(e,`Native snapshot entry ${t}`);Mr(r,Xq,`Native snapshot entry ${t}`);let i=ER(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Xf.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Ai(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!pR.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function RF(e,t){let r=Fr(e,`Native snapshot omission ${t}`);if(Mr(r,Qq,`Native snapshot omission ${t}`),!tF.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!rF.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:ER(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Ai(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function PF(e){let t=Fr(e,"Native snapshot omission overflow");if(Mr(t,Zq,"Native snapshot omission overflow"),typeof t.hash!="string"||!Xf.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Ns(t.count,"Native snapshot omission overflow count")}}function ys(e,t){let r=Fr(e,t);if(Mr(r,Uq,t),typeof r.hash!="string"||!Xf.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Ai(r.recordCount,`${t} recordCount`),n=Ai(r.storedRecordCount,`${t} storedRecordCount`),a=Ai(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function dR(e){let t=Fr(e,"Native Git selection evidence");if(Mr(t,Gq,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=ys(t.stageBefore,"Native Git selection stageBefore"),i=ys(t.combined,"Native Git selection combined"),n=ys(t.stageAfter,"Native Git selection stageAfter"),a=ys(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ys(t.finalCombined,"Native Git selection finalCombined"),s=ys(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!ia(r,n)||!ia(n,a)||!ia(i,o)||!ia(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function fR(e,t){let r=Fr(e,t);if(Mr(r,Yq,t),typeof r.hash!="string"||!Xf.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Ai(r.visitedNodeCount,`${t} visitedNodeCount`),n=Ai(r.recordCount,`${t} recordCount`),a=Ai(r.storedRecordCount,`${t} storedRecordCount`),o=Ai(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function CF(e){let t=Fr(e,"Native physical selection evidence");if(Mr(t,Kq,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=fR(t.before,"Native physical selection before"),i=fR(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!bR(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function Zi(e){let t=Fr(e,"Native content snapshot manifest");if(Mr(t,Lq,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!eF.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let E=Fr(t.capture,"Native content snapshot capture");if(Mr(E,zq,"Native content snapshot capture"),E.provider!=="git"&&E.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let P=E.gitSelection===void 0?void 0:dR(E.gitSelection),b=E.physicalSelection===void 0?void 0:CF(E.physicalSelection),k=null;if(E.projection!==void 0){let R=Fr(E.projection,"Native content snapshot projection");if(Mr(R,Jq,"Native content snapshot projection"),R.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");k={provider:"git",...R.selection===void 0?{}:{selection:dR(R.selection)}}}if(E.provider==="git"){if(b||k)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...P?{gitSelection:P}:{}}}else{if(P)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&k)throw new Error("Native physical-tree capture cannot combine selection and projection");r=k?{provider:"physical-tree",projection:k}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=Fr(t.limits,"Native content snapshot limits");Mr(i,Vq,"Native content snapshot limits");let n={maxFiles:Ns(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Ns(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Ns(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Ns(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Ns(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let E=Fr(t.policy,"Native snapshot policy");if(Mr(E,Wq,"Native snapshot policy"),E.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(E.include)||!Array.isArray(E.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=SR({include:E.include,exclude:E.exclude,hash:E.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(EF),s=t.omitted.map(RF),c=Ai(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:PF(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(E=>E.size>n.maxFileBytes)||o.reduce((E,P)=>E+P.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(E=>E.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>kg||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(E=>E.reason==="git-enumeration-limit"),f=s.filter(E=>E.reason==="git-selection-changed");for(let E of[...d,...f])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(E=>E.reason==="physical-enumeration-limit"),g=s.filter(E=>E.reason==="physical-selection-changed");for(let E of[...m,...g])if(E.path!=="."||E.size!==null||E.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,S=w?.status==="overflow"||w?.status==="overflow-and-changed",N=w?.status==="changed"||w?.status==="overflow-and-changed";if(S!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(N!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let y={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Pg(y)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return y}async function Qf(e,t,r={}){let i=Zi(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=Z.resolve(e.projectRoot),a=mR(r),o=vR(r.gitSelectionLimits),s=await yR(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(kR(s).filter(b=>Sl(e,b))),l=[...s.gitlinks].filter(b=>c.has(b)),u=[...s.nestedRepositories].filter(b=>Sl(e,b)),d=(b,k)=>k.some(R=>b===R||b.startsWith(`${R}/`)),f=b=>d(b,l),p=b=>d(b,u),v=[...i.entries.map(b=>b.path),...i.omitted.flatMap(b=>b.type==="directory"?[b.path,`${b.path}/`]:[b.path])].filter(b=>!c.has(b)&&!f(b)&&!p(b)),h=await uF(a,n,v),m=i.entries.filter(b=>!f(b.path)&&!p(b.path)&&Sl(e,b.path)&&(c.has(b.path)||!h.has(b.path)));await NR(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let b of l)g.push({path:b,size:null,type:"directory",reason:"legacy-gitlink-boundary"});m.sort((b,k)=>b.path.localeCompare(k.path,"en"));let w=i.omitted.filter(b=>f(b.path)||p(b.path)||!Sl(e,b.path)?!1:h.has(b.path)?c.has(b.path)||[...c].some(k=>k.startsWith(`${b.path}/`)):!0);for(let b of g)w.some(k=>k.path===b.path&&k.reason===b.reason)||w.push(b);w.sort((b,k)=>b.path.localeCompare(k.path,"en"));let S=i.omissionOverflow?.count??0,N=i.omissionOverflow?.hash??G("comet.native.snapshot-omission-overflow.v1");s.overflow&&(S+=s.overflow.count,N=Rl(N,"git-selection",{source:"git-selection",...s.overflow}));let y=b=>{S+=1,N=Rl(N,"omission",b)};for(;w.length>kg;){let b=Kf(w);if(b===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");y(b)}let E=()=>({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:w.length+S===0,entries:m,omitted:w,omittedCount:w.length+S,...S>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${N}`,hash:N,count:S}}:{}}),P=E();for(;Pg(P)>i.limits.maxManifestBytes;){let b=Kf(w);if(b===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");y(b),P=E()}return Zi(P)}function RR(e,t){if(!Mq.test(t))throw new Error(`Invalid Native change name: ${t}`);return Z.join(V(e,t),"baseline-manifest.json")}async function Zf(e,t={}){let r={maxFiles:t.limits?.maxFiles??Jf.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Jf.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Jf.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Jf.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=SR(t.policy),n=mR({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=vR(t.gitSelectionLimits),o=cF(t.physicalSelectionLimits);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=Z.resolve(e.projectRoot),c=await De.realpath(s),l=Z.resolve(e.nativeRoot),u=await De.realpath(l),d=Z.resolve(e.runtimeDir),f=Z.resolve(e.configFile),p=Z.join(s,".comet","current-change.json"),v=yF(s,t.denylist??[]),h=[],m=[],g=new Map,w=new Map,S=0,N=0,y=G("comet.native.snapshot-omission-overflow.v1"),E=0,P=!1,b=null,k=D=>{N+=1,y=Rl(y,"omission",D)},R=D=>{if(S+=1,m.length<kg){m.push(D);return}if(bg(D)){let O=Kf(m);if(O===null)throw new Error("Native snapshot has too many required selection-integrity omissions");k(O),m.push(D);return}k(D)},I=D=>{S+=D.count,N+=D.count,y=Rl(y,"git-selection",{source:"git-selection",...D})},C=D=>{N+=1,y=Rl(y,"manifest-entry",{reason:"manifest-size",entry:D})},Ne=async(D,O)=>{h.push(D),E+=D.size,g.set(D.path,O),P||(P=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(D.path))},oe=(D,O)=>{let M=h.findIndex($e=>$e.path===D);if(M<0)return;let[te]=h.splice(M,1);E-=te.size,g.delete(D),R(O)},ce=async(D,O,M,te)=>{if(!M.isFile()||M.isSymbolicLink()||!K(n))return;let $e;try{$e=await De.realpath(D)}catch(T){if(!K(n))return;if(!at(T)&&!nt(T))throw T;R({path:O,size:M.size,type:"file",reason:nt(T)?"changed-during-read":"unreadable"});return}if(!K(n)||!q(c,$e)||ci(u,$e))return;if(h.length>=r.maxFiles){R({path:O,size:M.size,type:"file",reason:"file-count"});return}if(M.size>r.maxFileBytes){R({path:O,size:M.size,type:"file",reason:"file-size"});return}if(E+M.size>r.maxTotalBytes){R({path:O,size:M.size,type:"file",reason:"total-size"});return}let de,Y,Ve;try{if(de=await SF($e,M.size,M,n),de.status==="budget-exhausted"||!K(n))return;if(de.status==="changed"){R({path:O,size:null,type:"file",reason:"changed-during-read"});return}if(!K(n)||(Ve=await De.realpath(D),!K(n)))return;Y=await De.lstat(D)}catch(T){if(!K(n))return;if(!at(T)&&!nt(T))throw T;R({path:O,size:M.size,type:"file",reason:nt(T)?"changed-during-read":"unreadable"});return}if(K(n)){if(de.bytes!==M.size||Ve!==$e||!ra(M,de.finalStat)||!ra(de.finalStat,Y)||!Y.isFile()||Y.isSymbolicLink()||Y.size!==M.size||Y.mtimeMs!==M.mtimeMs||Y.ctimeMs!==M.ctimeMs){R({path:O,size:Y.isFile()?Y.size:null,type:Y.isFile()?"file":"other",reason:"changed-during-read"});return}K(n)&&await Ne({path:O,hash:de.hash,size:Y.size,type:"file",...te===void 0?{}:{gitObjectId:te}},{kind:"file",target:D,realTarget:$e,stat:Y})}},Ue=async(D,O,M)=>{if(!K(n))return;let te,$e,de;try{if(te=await De.readlink(D,{encoding:"buffer"}),!K(n)||(de=await De.lstat(D),!K(n)))return;$e=await De.readlink(D,{encoding:"buffer"})}catch(T){if(!K(n))return;if(!at(T)&&!nt(T))throw T;R({path:O,size:null,type:"other",reason:nt(T)?"changed-during-read":"unreadable"});return}if(!K(n))return;if(!de.isSymbolicLink()||!ra(M,de)||de.mtimeMs!==M.mtimeMs||de.ctimeMs!==M.ctimeMs||!te.equals($e)){R({path:O,size:null,type:"other",reason:"changed-during-read"});return}let Y=te.byteLength;if(h.length>=r.maxFiles){R({path:O,size:Y,type:"other",reason:"file-count"});return}if(Y>r.maxFileBytes){R({path:O,size:Y,type:"other",reason:"file-size"});return}if(E+Y>r.maxTotalBytes){R({path:O,size:Y,type:"other",reason:"total-size"});return}let Ve=Yf("sha256").update("symlink\0").update(te).digest("hex");K(n)&&await Ne({path:O,hash:Ve,size:Y,type:"file"},{kind:"symlink",target:D,rawTarget:te,stat:de})},Ke=async()=>{for(let[D,O]of[...g]){if(!K(n))return;if(O.kind==="file"){let Y,Ve;try{if(Y=await De.realpath(O.target),!K(n))return;Ve=await De.lstat(O.target)}catch(T){if(!K(n))return;if(!at(T)&&!nt(T))throw T;oe(D,{path:D,size:null,type:"file",reason:at(T)?"unreadable":"changed-during-read"});continue}if(!K(n))return;(Y!==O.realTarget||!Ve.isFile()||Ve.isSymbolicLink()||!ra(O.stat,Ve)||Ve.size!==O.stat.size||Ve.mtimeMs!==O.stat.mtimeMs||Ve.ctimeMs!==O.stat.ctimeMs)&&oe(D,{path:D,size:Ve.isFile()?Ve.size:null,type:Ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(O.kind==="symlink"){let Y,Ve;try{if(Y=await De.lstat(O.target),!K(n))return;Ve=await De.readlink(O.target,{encoding:"buffer"})}catch(T){if(!K(n))return;if(!at(T)&&!nt(T))throw T;oe(D,{path:D,size:null,type:"other",reason:at(T)?"unreadable":"changed-during-read"});continue}if(!K(n))return;(!Y.isSymbolicLink()||!ra(O.stat,Y)||Y.mtimeMs!==O.stat.mtimeMs||Y.ctimeMs!==O.stat.ctimeMs||!O.rawTarget.equals(Ve))&&oe(D,{path:D,size:null,type:"other",reason:"changed-during-read"});continue}let M,te;try{if(M=await De.realpath(O.target),!K(n))return;te=await De.lstat(O.target)}catch{if(!K(n))return;oe(D,{path:D,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!K(n))return;if(!(M===O.realTarget&&te.isDirectory()&&!te.isSymbolicLink()&&ra(O.stat,te)&&q(c,M)&&!ci(u,M))){oe(D,{path:D,size:null,type:"directory",reason:"gitlink-changed"});continue}let de;try{if(!K(n))return;de=await cR(n,M)}catch(Y){if(bs(Y))throw Y;oe(D,{path:D,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!K(n))return;de.dirty?oe(D,{path:D,size:null,type:"directory",reason:"gitlink-dirty"}):de.hash!==O.hash&&oe(D,{path:D,size:null,type:"directory",reason:"gitlink-changed"})}for(let[D,O]of w){if(!K(n))return;try{let M=await De.lstat(O);if(!K(n))return;R({path:D,size:M.isFile()?M.size:null,type:M.isFile()?"file":M.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(M){if(!K(n))return;if(nt(M))continue;if(!at(M))throw M;R({path:D,size:null,type:"file",reason:"unreadable"})}}},jt=await yR(n,e,a,t.gitSelectionHooks);if(jt===null){let D=await oR({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let te of D.records){if(te.type!=="file"&&te.type!=="symlink"||g.has(te.path))continue;if(si(n)<1)break;if(!uR(i,te.path,n))continue;if(si(n)<1)break;let $e=Z.resolve(s,...te.path.split("/")),de;try{de=await De.lstat($e)}catch(Y){if(!K(n))break;if(!at(Y)&&!nt(Y))throw Y;R({path:te.path,size:null,type:"file",reason:nt(Y)?"changed-during-read":"unreadable"});continue}if(si(n)<1)break;if(te.type==="symlink"&&de.isSymbolicLink()){if(await Ue($e,te.path,de),si(n)<1)break;continue}if(te.type!=="file"||!de.isFile()||de.isSymbolicLink()){R({path:te.path,size:de.isFile()?de.size:null,type:de.isDirectory()?"directory":de.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ce($e,te.path,de),si(n)<1)break}si(n)>=1&&await Ke();let O=await oR({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:i,limits:o}),M=gF(D.evidence,O.evidence);b=M.evidence;for(let te of[...D.omissions,...O.omissions,...M.omissions])m.some($e=>$e.path===te.path&&$e.reason===te.reason)||R(te)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let D=t.incrementalBaseline,O=new Map,M=!1;if(D){let T=Zi(D);for(let Fe of T.entries)Fe.gitObjectId!==void 0&&O.set(Fe.path,Fe);M=O.size>0}let te=new Set,$e=!0;try{let T=await El(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(T.overflow)M=!1,$e=!1,O.clear();else for(let Fe of T.records){let We=Uf(Fe),Wt=We.indexOf(" "),$t=Wt<0?null:ks(We.slice(Wt+1));if(Wt!==1||$t===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");We[0]!=="H"&&te.add($t)}}catch(T){if(bs(T))throw T;M=!1,$e=!1,O.clear()}let de=new Set;try{let T=await Gf(n,s,["ls-files","--modified","-z"],Ng);for(let Fe of T.toString("utf8").split("\0")){let We=ks(Fe);We!==null&&de.add(We)}}catch{M=!1,$e=!1,O.clear()}let Y=new Set,Ve=new Set;for(let T of kR(jt)){if(g.has(T)||!Sl(e,T))continue;if(si(n)<1)break;if(!uR(i,T,n))continue;if(si(n)<1)break;let Fe=Z.resolve(s,...T.split("/"));if(Fe===f||Fe===p||ci(d,Fe)||v.some(gr=>ci(gr,Fe)))continue;if(jt.gitlinks.has(T)){if(h.length>=r.maxFiles){R({path:T,size:0,type:"file",reason:"file-count"});continue}let gr,Qu;try{[gr,Qu]=await Promise.all([De.realpath(Fe),De.lstat(Fe)])}catch{R({path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Qu.isSymbolicLink()||!Qu.isDirectory()||!q(c,gr)||ci(u,gr)){R({path:T,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Lo=await cR(n,gr);if(Lo.dirty){R({path:T,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Ne({path:T,hash:Lo.hash,size:0,type:"file"},{kind:"gitlink",target:Fe,realTarget:gr,stat:Qu,hash:Lo.hash})}catch(Lo){if(bs(Lo))throw Lo;R({path:T,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let We;try{We=await De.lstat(Fe)}catch(gr){if(nt(gr)&&jt.tracked.has(T)){w.set(T,Fe);continue}if(!at(gr)&&!nt(gr))throw gr;R({path:T,size:null,type:"file",reason:nt(gr)?"changed-during-read":"unreadable"});continue}if(We.isSymbolicLink()){await Ue(Fe,T,We);continue}if(!We.isFile()){jt.nestedRepositories.has(T)||R({path:T,size:null,type:"other",reason:"changed-during-read"});continue}let Wt=jt.trackedObjectIds.get(T),$t=Wt?O.get(T):void 0;if(M&&$t?.gitObjectId!==void 0&&$t.gitObjectId===Wt&&!te.has(T)&&!de.has(T)){if(h.length>=r.maxFiles){R({path:T,size:$t.size,type:"file",reason:"file-count"});continue}if($t.size>r.maxFileBytes){R({path:T,size:$t.size,type:"file",reason:"file-size"});continue}if(E+$t.size>r.maxTotalBytes){R({path:T,size:$t.size,type:"file",reason:"total-size"});continue}h.push({...$t}),E+=$t.size,Y.add(T);continue}let WN=$e&&!te.has(T)&&!de.has(T)?Wt:void 0;await ce(Fe,T,We,WN),WN!==void 0&&Ve.add(T)}if(await Ke(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await NR(n,e,a,jt,t.gitSelectionHooks?.outputChunkBytes),Y.size>0||M&&Ve.size>0){let T=await Gf(n,s,["ls-files","--modified","-z"],Ng),Fe=new Set;for(let We of T.toString("utf8").split("\0")){let Wt=ks(We);Wt!==null&&Fe.add(Wt)}for(let We of Y){if(!Fe.has(We))continue;let Wt=h.find($t=>$t.path===We);oe(We,{path:We,size:Wt?.size??null,type:"file",reason:"changed-during-read"})}for(let We of Ve){if(!Fe.has(We))continue;let Wt=h.find($t=>$t.path===We);Wt&&delete Wt.gitObjectId}}for(let T of jt.omissions)R(T);jt.overflow&&I(jt.overflow)}h.sort((D,O)=>D.path.localeCompare(O.path,"en")),m.sort((D,O)=>D.path.localeCompare(O.path,"en"));let aj=jt===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...jt.evidence?{gitSelection:jt.evidence}:{}},VN=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:aj,createdAt:(t.now??new Date).toISOString(),complete:S===0,limits:r,...i?{policy:i.manifest}:{},entries:h,omitted:m,omittedCount:S,...N>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${y}`,hash:y,count:N}}:{}}),Lp=VN();for(;Pg(Lp)>r.maxManifestBytes;){if(m.filter(O=>!bg(O)).length>0){let O=Math.max(1,Math.ceil(m.length/4));for(let M=0;M<O;M+=1){let te=Kf(m);if(te===null)break;k(te)}}else if(h.length>0){let O=Math.max(1,Math.ceil(h.length/4));for(let M of h.splice(-O))S+=1,C(M)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");Lp=VN()}return Lp}async function Es(e,t,r={}){let n=(await X(e.projectRoot))?.native.snapshot??Wv;return Zf(e,{...r,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Cg(e,t,r){let i=RR(e,t);await j(F(e,i),i),await fe(i,Zi(r))}async function Rs(e,t){let r=RR(e,t),i=F(e,r);await j(i,r);try{let n=await Bf({root:i,file:r,maxBytes:Fq,label:"Native baseline snapshot manifest"});return Zi(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var Jf,kg,Fq,Mq,Lq,Vq,Wq,zq,Jq,Gq,Uq,Kq,Yq,Xq,Qq,Zq,eF,tF,rF,Xf,pR,iF,Ss,Ng,nF,aF,oF,Sg,sF,mF,na=_(()=>{"use strict";Oe();tt();qr();Ir();Q();Yt();Nc();Jf={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},kg=1e3,Fq=8*1024*1024,Mq=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lq=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Vq=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Wq=new Set(["schema","include","exclude","hash"]),zq=new Set(["provider","gitSelection","physicalSelection","projection"]),Jq=new Set(["provider","selection"]),Gq=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Uq=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Kq=new Set(["schema","status","before","after"]),Yq=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Xq=new Set(["path","hash","size","type","gitObjectId"]),Qq=new Set(["path","size","type","reason"]),Zq=new Set(["ref","hash","count"]),eF=new Set(["change-created","legacy-migration","explicit"]),tF=new Set(["file","directory","other"]),rF=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"]),Xf=/^[a-f0-9]{64}$/u,pR=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,iF=new Set(["EACCES","EPERM"]),Ss=64*1024,Ng=64*1024,nF=6e4,aF=1e3,oF=2,Sg={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},sF={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};mF=(1n<<256n)-1n});var kr,Ps=_(()=>{"use strict";kr=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"})});var eh=_(()=>{"use strict"});var PR=_(()=>{"use strict"});var xg=_(()=>{"use strict";eh()});var CR=_(()=>{"use strict";eh();xg()});var jF,xR=_(()=>{"use strict";jF=Ha(Mn(),1);as();Vn();Ga()});import{promises as $F}from"node:fs";import OF from"node:path";function HF(e){return e.includes(`\r
|
|
190
190
|
`)?`\r
|
|
191
191
|
`:`
|
|
192
|
-
`}function DF(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function BF(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function qF(e){let t=[],r=!1;for(let i of DF(e)){let n=BF(i);if(n===_R){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(n===IR){if(!r)throw new Error("Comet .gitignore managed block is malformed");r=!1;continue}r||t.push(i)}if(r)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function TR(e){let t=HF(e),r=qF(e);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=t),r+[_R,"!/.comet/","/.comet/*","!/.comet/config.yaml",IR,""].join(t)}async function Ag(e){let t=OF.resolve(e),r=await Gi(t,Pl,{label:"project .gitignore",expected:"file"}),i="",n=new Uint8Array;r.exists&&(n=(await ki(t,Pl,AR,{label:"project .gitignore"})).bytes,i=Buffer.from(n).toString("utf8"));let a=TR(i);a!==i&&(await Ua(r.target,a,{containedRoot:t,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await ki(t,Pl,AR,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await Gi(t,Pl,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}}),await Gi(t,Pl,{label:"project .gitignore",expected:"file"}),await $F.access(r.target))}var Pl,AR,_R,IR,_g=_(()=>{"use strict";as();Ga();Pl=".gitignore",AR=4*1024*1024,_R="# >>> Comet managed project state >>>",IR="# <<< Comet managed project state <<<"});function MF(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function th(e,t){return(...r)=>{let i=FF;if(i===null)return t(...r);let n=MF(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var FF,Ig=_(()=>{"use strict";FF=null});import Xt from"path";function jR(e,t){let r=Xt.relative(e,t);return r===""||!Xt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Xt.sep}`)}function VF(e,t){let r=Xt.isAbsolute(t)?Xt.resolve(t):Xt.resolve(e,t),i=Xt.relative(Xt.resolve(e),r);return i===""||Xt.isAbsolute(i)||i===".."||i.startsWith(`..${Xt.sep}`)?null:i.replaceAll("\\","/")}function $R(e){return process.platform==="win32"?e.toLowerCase():e}async function rh(e,t,r=[]){let i=Xt.isAbsolute(t)?Xt.resolve(t):Xt.resolve(e,t),n=Xt.resolve(e);if(!jR(n,i)||r.some(c=>jR(Xt.resolve(c),i)))return null;let a=VF(e,t);if(!a)return null;let s=(await LF(e)).allow_paths.find(c=>{let l=$R(a),u=$R(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var LF,Tg=_(()=>{"use strict";Ig();is();LF=th("hookWritePolicy",async e=>(await Dv(e))?.hook??{allow_paths:[]})});var OR=_(()=>{"use strict";eh();as();PR();CR();Vn();xR();Ga();is();Mv();_g();Tg();qv();xg()});var HR=_(()=>{"use strict";OR();yc()});import zF from"path";function xl(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Cl(e,t){let r=xl(e,t);if(zF.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function JF(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function BR(e){if(!e.run_id)return null;let t=xl(e,"run_id"),r=xl(e,"skill"),i=xl(e,"skill_version"),n=xl(e,"skill_hash"),a=Cl(e,"pending_ref"),o=Cl(e,"trajectory_ref"),s=Cl(e,"context_ref"),c=Cl(e,"artifacts_ref"),l=Cl(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:DR(e,"current_step"),iteration:u,pending:DR(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:JF(e)}}var DR,q9,qR=_(()=>{"use strict";HR();DR=(e,t)=>{let r=e[t];return r==null?null:String(r)};q9=256*1024});function UF(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=BR(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function ih(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!GF.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return UF(t)}var GF,FR=_(()=>{"use strict";qR();Ps();GF=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{createHash as KF}from"node:crypto";import{constants as nh,promises as Qt}from"node:fs";import Sr from"node:path";import{TextDecoder as YF}from"node:util";function _l(e,t){let r=Sr.relative(e,t);return r===""||!Sr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Sr.sep}`)}function LR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Al(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function XF(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aa(e,t,r){let i=kr[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=Sr.resolve(e),a=Sr.resolve(n,...i.slice(8).split("/"));if(!_l(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function MR(e){let t=await Qt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Qt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function jg(e,t){let r=Sr.resolve(e),i=Sr.resolve(t);if(!_l(r,i))throw new Error("Native Run path is outside its change");let n=[await MR(r)],a=r;for(let o of Sr.relative(r,i).split(Sr.sep).filter(Boolean)){a=Sr.join(a,o);let s;try{s=await MR(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!_l(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function ah(e){for(let t of e){let r=await Qt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!XF(t,r)||await Qt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function QF(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function so(e,t,r,i,n){let a=await jg(e,Sr.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Qt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=LR(o),c=await Qt.realpath(t);if(!_l(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?nh.O_RDONLY:nh.O_RDONLY|nh.O_NOFOLLOW|nh.O_NONBLOCK,u;try{u=await Qt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Qt.lstat(t),Qt.realpath(t)]);if(await ah(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Al(s,d)||!Al(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let v=await QF(u,r,i);await n?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([u.stat(),Qt.lstat(t),Qt.realpath(t)]);if(await ah(a),!m.isFile()||m.isSymbolicLink()||g!==c||!Al(s,h)||!Al(s,m))throw new Error(`${i} changed while reading`);let w;try{w=new YF("utf-8",{fatal:!0}).decode(v)}catch(S){throw new Error(`${i} is not valid UTF-8`,{cause:S})}return{text:w,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function ZF(e,t,r){let i=await jg(e,Sr.dirname(t));if(!i)return{exists:!1};let n;try{n=await Qt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${r} must be a regular file`);let a=await Qt.realpath(t);if(!_l(i[0].realPath,a))throw new Error(`${r} resolves outside its change`);return await ah(i),{exists:!0,identity:LR(n),realPath:a}}async function eM(e,t,r,i){let n=await jg(e,Sr.dirname(t));if(!n){if(!r.exists)return;throw new Error(`${i} parent changed before commit`)}let a;try{a=await Qt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!r.exists)return;throw new Error(`${i} changed before commit`,{cause:o})}if(!r.exists||!a.isFile()||a.isSymbolicLink()||!Al(r.identity,a)||await Qt.realpath(t)!==r.realPath)throw new Error(`${i} changed before commit`);await ah(n)}async function oh(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let r=e.expected??await ZF(e.changeDir,e.file,e.label);if(r.exists&&r.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await xe(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await eM(e.changeDir,e.file,r,e.label)}});let i=await so(e.changeDir,e.file,e.maxBytes,e.label);if(!i||i.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function VR(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function WR(e){return`${JSON.stringify(e,null,2)}
|
|
192
|
+
`}function DF(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function BF(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function qF(e){let t=[],r=!1;for(let i of DF(e)){let n=BF(i);if(n===_R){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(n===IR){if(!r)throw new Error("Comet .gitignore managed block is malformed");r=!1;continue}r||t.push(i)}if(r)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function TR(e){let t=HF(e),r=qF(e);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=t),r+[_R,"!/.comet/","/.comet/*","!/.comet/config.yaml",IR,""].join(t)}async function Ag(e){let t=OF.resolve(e),r=await Ui(t,Pl,{label:"project .gitignore",expected:"file"}),i="",n=new Uint8Array;r.exists&&(n=(await Si(t,Pl,AR,{label:"project .gitignore"})).bytes,i=Buffer.from(n).toString("utf8"));let a=TR(i);a!==i&&(await Ua(r.target,a,{containedRoot:t,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await Si(t,Pl,AR,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await Ui(t,Pl,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}}),await Ui(t,Pl,{label:"project .gitignore",expected:"file"}),await $F.access(r.target))}var Pl,AR,_R,IR,_g=_(()=>{"use strict";as();Ga();Pl=".gitignore",AR=4*1024*1024,_R="# >>> Comet managed project state >>>",IR="# <<< Comet managed project state <<<"});function MF(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function th(e,t){return(...r)=>{let i=FF;if(i===null)return t(...r);let n=MF(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var FF,Ig=_(()=>{"use strict";FF=null});import Xt from"path";function jR(e,t){let r=Xt.relative(e,t);return r===""||!Xt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Xt.sep}`)}function VF(e,t){let r=Xt.isAbsolute(t)?Xt.resolve(t):Xt.resolve(e,t),i=Xt.relative(Xt.resolve(e),r);return i===""||Xt.isAbsolute(i)||i===".."||i.startsWith(`..${Xt.sep}`)?null:i.replaceAll("\\","/")}function $R(e){return process.platform==="win32"?e.toLowerCase():e}async function rh(e,t,r=[]){let i=Xt.isAbsolute(t)?Xt.resolve(t):Xt.resolve(e,t),n=Xt.resolve(e);if(!jR(n,i)||r.some(c=>jR(Xt.resolve(c),i)))return null;let a=VF(e,t);if(!a)return null;let s=(await LF(e)).allow_paths.find(c=>{let l=$R(a),u=$R(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var LF,Tg=_(()=>{"use strict";Ig();is();LF=th("hookWritePolicy",async e=>(await Dv(e))?.hook??{allow_paths:[]})});var OR=_(()=>{"use strict";eh();as();PR();CR();Vn();xR();Ga();is();Mv();_g();Tg();qv();xg()});var HR=_(()=>{"use strict";OR();yc()});import zF from"path";function xl(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Cl(e,t){let r=xl(e,t);if(zF.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function JF(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function BR(e){if(!e.run_id)return null;let t=xl(e,"run_id"),r=xl(e,"skill"),i=xl(e,"skill_version"),n=xl(e,"skill_hash"),a=Cl(e,"pending_ref"),o=Cl(e,"trajectory_ref"),s=Cl(e,"context_ref"),c=Cl(e,"artifacts_ref"),l=Cl(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:DR(e,"current_step"),iteration:u,pending:DR(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:JF(e)}}var DR,q9,qR=_(()=>{"use strict";HR();DR=(e,t)=>{let r=e[t];return r==null?null:String(r)};q9=256*1024});function UF(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)},r=BR(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function ih(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!GF.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return UF(t)}var GF,FR=_(()=>{"use strict";qR();Ps();GF=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{createHash as KF}from"node:crypto";import{constants as nh,promises as Qt}from"node:fs";import Sr from"node:path";import{TextDecoder as YF}from"node:util";function _l(e,t){let r=Sr.relative(e,t);return r===""||!Sr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Sr.sep}`)}function LR(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Al(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function XF(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aa(e,t,r){let i=kr[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=Sr.resolve(e),a=Sr.resolve(n,...i.slice(8).split("/"));if(!_l(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function MR(e){let t=await Qt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await Qt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function jg(e,t){let r=Sr.resolve(e),i=Sr.resolve(t);if(!_l(r,i))throw new Error("Native Run path is outside its change");let n=[await MR(r)],a=r;for(let o of Sr.relative(r,i).split(Sr.sep).filter(Boolean)){a=Sr.join(a,o);let s;try{s=await MR(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!_l(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function ah(e){for(let t of e){let r=await Qt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!XF(t,r)||await Qt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function QF(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function so(e,t,r,i,n){let a=await jg(e,Sr.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await Qt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=LR(o),c=await Qt.realpath(t);if(!_l(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?nh.O_RDONLY:nh.O_RDONLY|nh.O_NOFOLLOW|nh.O_NONBLOCK,u;try{u=await Qt.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),Qt.lstat(t),Qt.realpath(t)]);if(await ah(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!Al(s,d)||!Al(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let v=await QF(u,r,i);await n?.beforeFinalCheck?.();let[h,m,g]=await Promise.all([u.stat(),Qt.lstat(t),Qt.realpath(t)]);if(await ah(a),!m.isFile()||m.isSymbolicLink()||g!==c||!Al(s,h)||!Al(s,m))throw new Error(`${i} changed while reading`);let w;try{w=new YF("utf-8",{fatal:!0}).decode(v)}catch(S){throw new Error(`${i} is not valid UTF-8`,{cause:S})}return{text:w,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function ZF(e,t,r){let i=await jg(e,Sr.dirname(t));if(!i)return{exists:!1};let n;try{n=await Qt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${r} must be a regular file`);let a=await Qt.realpath(t);if(!_l(i[0].realPath,a))throw new Error(`${r} resolves outside its change`);return await ah(i),{exists:!0,identity:LR(n),realPath:a}}async function eM(e,t,r,i){let n=await jg(e,Sr.dirname(t));if(!n){if(!r.exists)return;throw new Error(`${i} parent changed before commit`)}let a;try{a=await Qt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!r.exists)return;throw new Error(`${i} changed before commit`,{cause:o})}if(!r.exists||!a.isFile()||a.isSymbolicLink()||!Al(r.identity,a)||await Qt.realpath(t)!==r.realPath)throw new Error(`${i} changed before commit`);await ah(n)}async function oh(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let r=e.expected??await ZF(e.changeDir,e.file,e.label);if(r.exists&&r.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await xe(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await eM(e.changeDir,e.file,r,e.label)}});let i=await so(e.changeDir,e.file,e.maxBytes,e.label);if(!i||i.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function VR(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function WR(e){return`${JSON.stringify(e,null,2)}
|
|
193
193
|
`}function oa(e){return ih(e)}async function pt(e,t){let r=aa(e,"stateRef"),i=await so(e,r,Ht.runStateBytes,"Native Run state",t);return i?ih(VR(i.text,"Native Run state")):null}async function co(e,t,r){let i=ih(t);await oh({changeDir:e,file:aa(e,"stateRef"),content:WR(i),maxBytes:Ht.runStateBytes,label:"Native Run state",hooks:r})}async function Zt(e,t,r){let i=aa(e,"trajectoryRef",t),n=await so(e,i,Ht.trajectoryBytes,"Native Run trajectory",r);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Ht.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ht.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 zR(e,t,r){return(await so(e,aa(e,"trajectoryRef",t),Ht.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function JR(e,t,r,i,n){if(!/^[a-f0-9]{64}$/u.test(i))throw new Error("Native Run trajectory expected hash is invalid");let a=aa(e,"trajectoryRef",t),o=await so(e,a,Ht.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(KF("sha256").update(o.text,"utf8").digest("hex")!==i)throw new Error("Native Run trajectory changed before repair");await oh({changeDir:e,file:a,content:r,maxBytes:Ht.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function GR(e,t,r,i){let n=aa(e,"trajectoryRef",t),a=`${JSON.stringify(r)}
|
|
194
|
-
`;if(Buffer.byteLength(a,"utf8")>Ht.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ht.trajectoryEventBytes} bytes`);let o=await so(e,n,Ht.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ht.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ht.trajectoryEvents} events`);await oh({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Ht.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:i})}async function Cs(e,t,r){let i=await so(e,aa(e,"checkpointRef",t),Ht.checkpointBytes,"Native Run checkpoint",r);return i?VR(i.text,"Native Run checkpoint"):null}async function UR(e,t,r,i){await oh({changeDir:e,file:aa(e,"checkpointRef",t),content:WR(r),maxBytes:Ht.checkpointBytes,label:"Native Run checkpoint",hooks:i})}var Ht,
|
|
195
|
-
`)])}catch(d){if(!oM(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:$g(t),targetHash:$g(l),tailHash:$g(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function KR(e,t){let r=nM(e,t);await j(F(e,r),r);let i=V(e,t),n=await zR(i,kr.trajectoryRef);return n===null?{status:"clean",file:r}:sM(r,Buffer.from(n))}async function xs(e,t){let r=await KR(e,t);return"inspection"in r?r.inspection:r}async function ch(e,t){let r=await xs(e,t);if(r.status!=="clean")throw new sh(r)}async function YR(e,t,r){return $(e,`repair trajectory tail for ${t}`,async()=>{let i=await KR(e,t);if(!("inspection"in i)){if(i.status==="clean")return null;throw new sh(i)}try{await JR(V(e,t),kr.trajectoryRef,i.targetContent,i.inspection.originalHash,{beforeCommit:r?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await xs(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return i.inspection})}var iM,sh,Il=_(()=>{"use strict";Ps();it();Q();
|
|
196
|
-
${t}`).digest("hex")}async function QR(e,t){let r=await lh.realpath(t),i=await lh.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hg==="win32"?
|
|
194
|
+
`;if(Buffer.byteLength(a,"utf8")>Ht.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Ht.trajectoryEventBytes} bytes`);let o=await so(e,n,Ht.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Ht.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Ht.trajectoryEvents} events`);await oh({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Ht.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:i})}async function Cs(e,t,r){let i=await so(e,aa(e,"checkpointRef",t),Ht.checkpointBytes,"Native Run checkpoint",r);return i?VR(i.text,"Native Run checkpoint"):null}async function UR(e,t,r,i){await oh({changeDir:e,file:aa(e,"checkpointRef",t),content:WR(r),maxBytes:Ht.checkpointBytes,label:"Native Run checkpoint",hooks:i})}var Ht,en=_(()=>{"use strict";Ps();FR();Oe();Ir();Ht={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});import{createHash as tM}from"crypto";import rM from"path";function $g(e){return tM("sha256").update(e).digest("hex")}function nM(e,t){if(!iM.test(t))throw new Error(`Invalid Native change name: ${t}`);return rM.join(V(e,t),"trajectory.jsonl")}function aM(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function oM(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function sM(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=aM(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
195
|
+
`)])}catch(d){if(!oM(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:$g(t),targetHash:$g(l),tailHash:$g(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function KR(e,t){let r=nM(e,t);await j(F(e,r),r);let i=V(e,t),n=await zR(i,kr.trajectoryRef);return n===null?{status:"clean",file:r}:sM(r,Buffer.from(n))}async function xs(e,t){let r=await KR(e,t);return"inspection"in r?r.inspection:r}async function ch(e,t){let r=await xs(e,t);if(r.status!=="clean")throw new sh(r)}async function YR(e,t,r){return $(e,`repair trajectory tail for ${t}`,async()=>{let i=await KR(e,t);if(!("inspection"in i)){if(i.status==="clean")return null;throw new sh(i)}try{await JR(V(e,t),kr.trajectoryRef,i.targetContent,i.inspection.originalHash,{beforeCommit:r?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await xs(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return i.inspection})}var iM,sh,Il=_(()=>{"use strict";Ps();it();Q();en();iM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sh=class extends Error{constructor(r){super(r.status==="repairable"?`Native trajectory has an incomplete final line at ${r.file}:${r.line}; run doctor --repair`:`Native trajectory is invalid at ${r.file}:${r.line}: ${r.message}`);this.inspection=r;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"}});import{createHash as cM}from"node:crypto";import{promises as lh}from"node:fs";import tn from"node:path";function As(e){return uM.has(e)}function eP(e,t){let r=tn.relative(e,t);return tn.isAbsolute(r)||r===".."||r.startsWith(`..${tn.sep}`)?null:r.replaceAll("\\","/")||"."}function tP(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function rP(e,t){if(e.length===0||tP(e)||e.includes("\\")||tn.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=tn.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Dg(e,t){return cM("sha256").update(`${e}
|
|
196
|
+
${t}`).digest("hex")}async function QR(e,t){let r=await lh.realpath(t),i=await lh.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hg==="win32"?tn.normalize(r).toLowerCase():r;return Dg(e,`${n}
|
|
197
197
|
${i.dev}
|
|
198
198
|
${i.ino}
|
|
199
|
-
${i.birthtimeMs}`)}async function ZR(e,t){let r=await lh.realpath(t),i=await lh.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hg==="win32"?
|
|
199
|
+
${i.birthtimeMs}`)}async function ZR(e,t){let r=await lh.realpath(t),i=await lh.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Hg==="win32"?tn.normalize(r).toLowerCase():r;return Dg(e,n)}function dM(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Og(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||tP(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function iP(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Og(e.changeBranch,"Native workspace change branch"),Og(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function fM(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!XR.test(t.baseCommit)||typeof t.targetCommit!="string"||!XR.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Og(t.targetBranch,"Native workspace Git target branch")}function jl(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Tl.test(String(t.projectRootId))||!Tl.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");dM(t.capturedAt),rP(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Tl.test(String(t.projectRootPathId))||a&&!Tl.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Tl.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&fM(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(iP(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function _s(e,t){return tn.join(V(e,t),"workspace.json")}function hM(e,t){let r=_s(e,t),i=F(e,r),n=eP(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:rP(n,"Native workspace file ref")}}async function nP(e,t){try{let r=hM(e,t),i=await re({root:r.root,ref:r.ref,maxBytes:lM});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function $l(e,t){let r=ne(e.projectRoot),i={projectRoot:tn.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await Dt(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await _i({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Bg(e,t){let r=await nP(e,t);if(r===null)return!1;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Native workspace identity must be an object");return r.schema==="comet.native.workspace.v1"?!0:(jl(r),r.schema==="comet.native.workspace.v3"?!1:r.projectRootPathId===void 0||r.nativeRootPathId===void 0)}async function aP(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=eP(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ne(e.paths.projectRoot),i=r.isGitWorktree?yi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:yi(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([QR("comet.native.workspace-project-root.v2",e.paths.projectRoot),QR("comet.native.workspace-native-root.v2",e.paths.nativeRoot),ZR("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),ZR("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&iP(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Dg("comet.native.workspace-session.v2",`${s}
|
|
200
200
|
${c}
|
|
201
|
-
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return jl(p),p}async function uh(e){let t=await aP(e),r=_s(e.paths,e.name),i=F(e.paths,r);return await j(i,r),await fe(r,t,{containedRoot:i}),t}async function Dt(e,t){let r=await nP(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(jl(r),r)}async function oP(e){return await Bg(e.paths,e.name)?uh(e):null}async function sa(e){jl(e.identity);let t=await aP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Hg==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function Ai(e){if(jl(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await sa(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ne(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function sP(e,t){let r=await Dt(e,t);if(r===null)return null;let i=await Ai({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var Tl,XR,lM,Hg,uM,Lr=_(()=>{"use strict";zt();$e();Jt();it();Q();Tl=/^[a-f0-9]{64}$/u,XR=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,lM=16*1024,Hg=process.platform,uM=new Set(["workspace-root-changed","workspace-inspection-unavailable"])});import{promises as Ol}from"fs";import Bt from"path";function ql(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hP(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function uo(e){if(!fP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function bM(e){if(!fP.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function pP(e,t){if(e.length===0||Bt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kM(e,t){let r=ql(e,`spec_changes[${t}]`);if(hP(r,vM,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(bM(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&pP(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Fg.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Fg.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function SM(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Mg(e,t){if(hP(e,t,lt),typeof e.name!="string")throw new Error("Native change name is required");if(uo(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!gM.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!wM.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(kM),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!yM.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&pP(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SM(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ro(e){let t=ql(e,lt);if(t.schema!==Kt)throw new Error(`Expected ${Kt}`);return{schema:Kt,...Mg(t,pM)}}function Bl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qg(e,t,r){if(e===null)return null;let i=typeof e=="string"?NM.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function EM(e){if(e==null)return null;if(typeof e!="string"||!Fg.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function RM(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Ri(e){let t=ql(e,lt);if(t.schema!==Xe)throw new Error(`Expected ${Xe}`);if(Bl(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Xe} minimum_runtime_version must be 2`);return{schema:Xe,minimum_runtime_version:2,revision:Bl(t.revision,"Native v2 revision"),...Mg(t,dP)}}function cr(e){let t=ql(e,lt);if(t.schema!==Ye){if(t.schema===Kt||t.schema===Xe){let o=t.schema===Kt?ro(t):Ri(t);throw new Hl(o.name,o.schema)}throw new ci(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Bl(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new ci(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Bl(t.revision,"Native revision"),n=Mg(t,mM),a=EM(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:i,verification_protocol:RM(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:qg(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:qg(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:qg(t.partial_allowance,"Native partial_allowance","allowances")}}function mP(e){let t=ql(e,lt);if(t.schema===Kt){let n=ro(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Xe){let n=Ri(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new ci(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Bl(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new ci(t.schema,r).message};let i=cr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function lo(e){let t=cr(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function fh(e){let t=Ri(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function se(e,t){uo(t);let r=Bt.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function js(e,t){let r=V(e,t),i=Bt.join(r,"schema-migration.json");await j(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ol.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function $s(e,t){let r=V(e,t),i=Bt.join(r,"checkpoint-journal.json");await j(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ol.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function hh(e,t=Bt.dirname(e)){let r=Bt.relative(t,e).split(Bt.sep).join("/"),i=await re({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,dh.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Vr(e,t){let r=Bt.join(se(e,t),lt);await j(e.nativeRoot,r);let i=mP(await hh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await js(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await PM(e,i.state),i)}async function fo(e,t){let r=Bt.join(se(e,t),lt);await j(e.nativeRoot,r);let i=mP(await hh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function PM(e,t){if(await Rs(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function De(e,t){let r=await Vr(e,t);if(r.status==="migration-required")throw new Hl(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new ci(r.schema,r.minimumRuntimeVersion);return await sP(e,t),r.state}async function vP(e,t,r){let i={...t,schema:Ye,minimum_runtime_version:3,revision:r+1},n=await rR({expectedRevision:r,next:i,read:async()=>{let a=cr(await hh(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>xe(e,(0,dh.stringify)(lo(a))),equals:(a,o)=>JSON.stringify(lo(a))===JSON.stringify(lo(o)),conflict:a=>new Dl(t.name,r,a)});return Object.assign(t,n),n}async function Fl(e,t,r,i){if(await cs(e.projectRoot),await js(e,t.name))throw new Hl(t.name,t.schema);if(!i?.allowPendingCheckpointRecovery&&await $s(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await De(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await ch(e,t.name);let a=Bt.join(se(e,t.name),lt);return await j(e.nativeRoot,a),vP(a,t,r)}async function gP(e,t){return vP(e,t,t.revision)}async function wP(e){return cr(await hh(e))}async function CM(e){let t;try{let i=await lr({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),t=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function yP(e){let t=[];for(let r of await CM(e)){let i=await fo(e,r);if(!i.state){if(await lP(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await Dt(e,r);if(!(!n&&await lP(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await Ai({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await sa({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}function cP(e,t){let r=Bt.resolve(e),i=Bt.resolve(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function lP(e,t){for(let r of kt(e.projectRoot))if(!cP(r,e.projectRoot))try{let i=await X(r);if(!i)continue;let n=await pe(r,i.native.artifact_root),a=Bt.join(n.changesDir,t),o=Bt.join(a,"comet-state.yaml");try{let l=await Ol.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ol.readFile(Bt.join(Oe(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&cP(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Ol.access(Bt.join(a,lt));let s=await Dt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Ai({paths:n,identity:s})).state==="aligned")return!0;continue}if((await sa({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var dh,uP,pM,dP,mM,vM,gM,wM,yM,lt,Fg,fP,NM,Hl,ci,Dl,Is,Ts,j8,Ee=_(()=>{"use strict";dh=Ha(Mn(),1);zt();Jt();$e();Va();tt();it();Q();Yt();iR();na();Il();Lr();wl();uP=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],pM=new Set(uP),dP=new Set([...uP,"minimum_runtime_version","revision"]),mM=new Set([...dP,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),vM=new Set(["capability","operation","source","base_hash"]),gM=new Set(["shape","build","verify","archive"]),wM=new Set(["implicit","confirmed"]),yM=new Set(["pending","pass","fail"]),lt="comet-state.yaml",Fg=/^[a-f0-9]{64}$/u,fP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NM=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Hl=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},ci=class extends Error{constructor(r,i){super(r!==Ye||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Dl=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Is=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ts=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;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"},j8=Qc("en")});import{execFileSync as IM}from"node:child_process";function RP(e,t){try{return IM("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:TM,maxBuffer:jM,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Jg(e,t,i)}}function A(e,t){return RP(e,t).trim()}function PP(e){return A(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Gg(e,t){A(e,["check-ref-format","--branch",t])}function Os(e){let t=RP(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function CP(e,t){try{let i=A(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=A(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var TM,jM,Jg,tn=_(()=>{"use strict";TM=3e4,jM=8*1024*1024,Jg=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{createHash as $M}from"node:crypto";import{lstatSync as OM,readFileSync as xP,promises as Ug}from"node:fs";import Ll from"node:path";function Hs(e){try{if(A(e,["ls-files","--",Vl]))return!1;let t=Ll.join(e,Vl),r=OM(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(xP(AP(e),"utf8")).hash===_P(xP(t))}catch{return!1}}async function ph(e){let t=Ll.join(e,Vl),r;try{r=await Ug.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=AP(e);await Ug.mkdir(Ll.dirname(i),{recursive:!0}),await fe(i,{hash:_P(r)},{containedRoot:e})}function Er(e,t=[]){return Os(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===Vl&&Hs(e))}async function Wl(e){Hs(e)&&await Ug.unlink(Ll.join(e,Vl))}var Vl,AP,_P,ho=_(()=>{"use strict";tn();$e();Vl=".comet/config.yaml",AP=e=>Ll.join(e,".comet","runtime","native","workspace-config.json"),_P=e=>$M("sha256").update(e).digest("hex")});import{spawn as Kg}from"node:child_process";import{existsSync as IP}from"node:fs";import po from"node:path";function Yg(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function FM(e){let t=(Yg(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function MM(e,t,r){let n=po.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Yg(t,"PATH")??"").split(po.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=po.win32.extname(e)?[e]:FM(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?po.join(s,c):po.resolve(r,c)))}function Xg(e,t,r){return MM(e,t,r).find(i=>IP(i))??e}function LM(e){let t=Yg(e,"SystemRoot");if(t){let r=po.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(IP(r))return r}return"powershell.exe"}function Qg(e){if(e.some(t=>BM.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function VM(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(qM,"utf16le").toString("base64");return Kg(LM(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Zg(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Kg(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=Xg(e,i,r.cwd),a=po.win32.extname(n).toLowerCase();return DM.has(a)&&Qg(t),HM.has(a)?VM(n,t,{cwd:r.cwd,env:i}):Kg(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var HM,DM,BM,qM,mh=_(()=>{"use strict";HM=new Set([".bat",".cmd",".ps1"]),DM=new Set([".bat",".cmd"]),BM=/[&|<>()^%"!\r\n]/u,qM=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_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("; ")});import{spawn as WM}from"node:child_process";import ew from"node:path";async function zl(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&ew.win32.isAbsolute(r)?ew.win32.resolve(r):"C:\\Windows",n=ew.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=WM(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),zM)}catch{u(!1)}});for(let o=0;o<JM;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var zM,JM,tw=_(()=>{"use strict";zM=1e3,JM=2});function mt(e){return e.replace(GM,"$1 [REDACTED]").replace(UM,"[REDACTED PRIVATE KEY]").replace(KM,"$1[REDACTED]@").replace(YM,"[REDACTED TOKEN]").replace(XM,'$1"[REDACTED]"').replace(QM,"$1$2$1$3$4[REDACTED]$4").replace(ZM,"$1$2[REDACTED]")}var GM,UM,KM,YM,XM,QM,ZM,rn=_(()=>{"use strict";GM=/\b(Bearer|Basic)\s+[^\s"']+/giu,UM=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,KM=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,YM=/\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,XM=/("(?:[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,QM=/(["'])((?:[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,ZM=/\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});import{createWriteStream as eL,promises as tL}from"node:fs";import Rr from"node:path";function TP(e,t){let r=Rr.relative(e,t);return r===""||!Rr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Rr.sep}`)}function jP(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function vh(e,t){if(t.length===0||t.includes("\\")||Rr.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Rr.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Rr.resolve(e),i=Rr.resolve(r,...t.split("/"));if(!TP(r,i))throw new Error("Native check cwd escaped the project root");return i}function Jl(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function rw(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=mt(r);return rL.test(r)&&(t=!0),i})}function la(e,t){if(jP(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return vh(e,t.cwdRef)}async function mo(e){let{plan:t}=e;jP(e.operationId,"Native check operation ID");let r=la(e.projectRoot,t),i=Rr.join(e.runtimeDir,"logs","checks"),n=Rr.join(i,`${e.operationId}-${t.id}.log`);if(!TP(Rr.resolve(e.runtimeDir),Rr.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await tL.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=eL(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Zg(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let u=!1,d=null,f=null,p=Promise.resolve(),v=!1,h=setTimeout(()=>{u=!0,zl(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(h.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{d=m,o.write(`
|
|
201
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return jl(p),p}async function uh(e){let t=await aP(e),r=_s(e.paths,e.name),i=F(e.paths,r);return await j(i,r),await fe(r,t,{containedRoot:i}),t}async function Dt(e,t){let r=await nP(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(jl(r),r)}async function oP(e){return await Bg(e.paths,e.name)?uh(e):null}async function sa(e){jl(e.identity);let t=await aP({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),Hg==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function _i(e){if(jl(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await sa(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ne(e.paths.projectRoot);return e.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function sP(e,t){let r=await Dt(e,t);if(r===null)return null;let i=await _i({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var Tl,XR,lM,Hg,uM,Lr=_(()=>{"use strict";zt();Oe();Jt();it();Q();Tl=/^[a-f0-9]{64}$/u,XR=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,lM=16*1024,Hg=process.platform,uM=new Set(["workspace-root-changed","workspace-inspection-unavailable"])});import{promises as Ol}from"fs";import Bt from"path";function ql(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hP(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function uo(e){if(!fP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function bM(e){if(!fP.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function pP(e,t){if(e.length===0||Bt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kM(e,t){let r=ql(e,`spec_changes[${t}]`);if(hP(r,vM,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(bM(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&pP(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Fg.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Fg.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function SM(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Mg(e,t){if(hP(e,t,lt),typeof e.name!="string")throw new Error("Native change name is required");if(uo(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!gM.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!wM.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(kM),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!yM.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&pP(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SM(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function ro(e){let t=ql(e,lt);if(t.schema!==Kt)throw new Error(`Expected ${Kt}`);return{schema:Kt,...Mg(t,pM)}}function Bl(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qg(e,t,r){if(e===null)return null;let i=typeof e=="string"?NM.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function EM(e){if(e==null)return null;if(typeof e!="string"||!Fg.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function RM(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Pi(e){let t=ql(e,lt);if(t.schema!==Xe)throw new Error(`Expected ${Xe}`);if(Bl(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Xe} minimum_runtime_version must be 2`);return{schema:Xe,minimum_runtime_version:2,revision:Bl(t.revision,"Native v2 revision"),...Mg(t,dP)}}function cr(e){let t=ql(e,lt);if(t.schema!==Ye){if(t.schema===Kt||t.schema===Xe){let o=t.schema===Kt?ro(t):Pi(t);throw new Hl(o.name,o.schema)}throw new li(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Bl(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new li(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Bl(t.revision,"Native revision"),n=Mg(t,mM),a=EM(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ye,minimum_runtime_version:3,revision:i,verification_protocol:RM(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:qg(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:qg(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:qg(t.partial_allowance,"Native partial_allowance","allowances")}}function mP(e){let t=ql(e,lt);if(t.schema===Kt){let n=ro(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema===Xe){let n=Pi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ye}`}}if(t.schema!==Ye){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new li(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Bl(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new li(t.schema,r).message};let i=cr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function lo(e){let t=cr(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function fh(e){let t=Pi(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function se(e,t){uo(t);let r=Bt.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function js(e,t){let r=V(e,t),i=Bt.join(r,"schema-migration.json");await j(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ol.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function $s(e,t){let r=V(e,t),i=Bt.join(r,"checkpoint-journal.json");await j(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await Ol.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function hh(e,t=Bt.dirname(e)){let r=Bt.relative(t,e).split(Bt.sep).join("/"),i=await re({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,dh.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Vr(e,t){let r=Bt.join(se(e,t),lt);await j(e.nativeRoot,r);let i=mP(await hh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await js(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await PM(e,i.state),i)}async function fo(e,t){let r=Bt.join(se(e,t),lt);await j(e.nativeRoot,r);let i=mP(await hh(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function PM(e,t){if(await Rs(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Be(e,t){let r=await Vr(e,t);if(r.status==="migration-required")throw new Hl(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new li(r.schema,r.minimumRuntimeVersion);return await sP(e,t),r.state}async function vP(e,t,r){let i={...t,schema:Ye,minimum_runtime_version:3,revision:r+1},n=await rR({expectedRevision:r,next:i,read:async()=>{let a=cr(await hh(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>xe(e,(0,dh.stringify)(lo(a))),equals:(a,o)=>JSON.stringify(lo(a))===JSON.stringify(lo(o)),conflict:a=>new Dl(t.name,r,a)});return Object.assign(t,n),n}async function Fl(e,t,r,i){if(await cs(e.projectRoot),await js(e,t.name))throw new Hl(t.name,t.schema);if(!i?.allowPendingCheckpointRecovery&&await $s(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Be(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await ch(e,t.name);let a=Bt.join(se(e,t.name),lt);return await j(e.nativeRoot,a),vP(a,t,r)}async function gP(e,t){return vP(e,t,t.revision)}async function wP(e){return cr(await hh(e))}async function CM(e){let t;try{let i=await lr({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),t=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function yP(e){let t=[];for(let r of await CM(e)){let i=await fo(e,r);if(!i.state){if(await lP(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await Dt(e,r);if(!(!n&&await lP(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await _i({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await sa({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}function cP(e,t){let r=Bt.resolve(e),i=Bt.resolve(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function lP(e,t){for(let r of kt(e.projectRoot))if(!cP(r,e.projectRoot))try{let i=await X(r);if(!i)continue;let n=await pe(r,i.native.artifact_root),a=Bt.join(n.changesDir,t),o=Bt.join(a,"comet-state.yaml");try{let l=await Ol.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ol.readFile(Bt.join(He(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&cP(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Ol.access(Bt.join(a,lt));let s=await Dt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await _i({paths:n,identity:s})).state==="aligned")return!0;continue}if((await sa({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}var dh,uP,pM,dP,mM,vM,gM,wM,yM,lt,Fg,fP,NM,Hl,li,Dl,Is,Ts,j8,Ee=_(()=>{"use strict";dh=Ha(Mn(),1);zt();Jt();Oe();Va();tt();it();Q();Yt();iR();na();Il();Lr();wl();uP=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],pM=new Set(uP),dP=new Set([...uP,"minimum_runtime_version","revision"]),mM=new Set([...dP,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),vM=new Set(["capability","operation","source","base_hash"]),gM=new Set(["shape","build","verify","archive"]),wM=new Set(["implicit","confirmed"]),yM=new Set(["pending","pass","fail"]),lt="comet-state.yaml",Fg=/^[a-f0-9]{64}$/u,fP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NM=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Hl=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},li=class extends Error{constructor(r,i){super(r!==Ye||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Dl=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Is=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ts=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;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"},j8=Qc("en")});import{execFileSync as IM}from"node:child_process";function RP(e,t){try{return IM("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:TM,maxBuffer:jM,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Jg(e,t,i)}}function A(e,t){return RP(e,t).trim()}function PP(e){return A(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Gg(e,t){A(e,["check-ref-format","--branch",t])}function Os(e){let t=RP(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function CP(e,t){try{let i=A(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=A(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var TM,jM,Jg,rn=_(()=>{"use strict";TM=3e4,jM=8*1024*1024,Jg=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{createHash as $M}from"node:crypto";import{lstatSync as OM,readFileSync as xP,promises as Ug}from"node:fs";import Ll from"node:path";function Hs(e){try{if(A(e,["ls-files","--",Vl]))return!1;let t=Ll.join(e,Vl),r=OM(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(xP(AP(e),"utf8")).hash===_P(xP(t))}catch{return!1}}async function ph(e){let t=Ll.join(e,Vl),r;try{r=await Ug.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=AP(e);await Ug.mkdir(Ll.dirname(i),{recursive:!0}),await fe(i,{hash:_P(r)},{containedRoot:e})}function Er(e,t=[]){return Os(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===Vl&&Hs(e))}async function Wl(e){Hs(e)&&await Ug.unlink(Ll.join(e,Vl))}var Vl,AP,_P,ho=_(()=>{"use strict";rn();Oe();Vl=".comet/config.yaml",AP=e=>Ll.join(e,".comet","runtime","native","workspace-config.json"),_P=e=>$M("sha256").update(e).digest("hex")});import{spawn as Kg}from"node:child_process";import{existsSync as IP}from"node:fs";import po from"node:path";function Yg(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function FM(e){let t=(Yg(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function MM(e,t,r){let n=po.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Yg(t,"PATH")??"").split(po.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=po.win32.extname(e)?[e]:FM(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?po.join(s,c):po.resolve(r,c)))}function Xg(e,t,r){return MM(e,t,r).find(i=>IP(i))??e}function LM(e){let t=Yg(e,"SystemRoot");if(t){let r=po.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(IP(r))return r}return"powershell.exe"}function Qg(e){if(e.some(t=>BM.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function VM(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(qM,"utf16le").toString("base64");return Kg(LM(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Zg(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Kg(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=Xg(e,i,r.cwd),a=po.win32.extname(n).toLowerCase();return DM.has(a)&&Qg(t),HM.has(a)?VM(n,t,{cwd:r.cwd,env:i}):Kg(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var HM,DM,BM,qM,mh=_(()=>{"use strict";HM=new Set([".bat",".cmd",".ps1"]),DM=new Set([".bat",".cmd"]),BM=/[&|<>()^%"!\r\n]/u,qM=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_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("; ")});import{spawn as WM}from"node:child_process";import ew from"node:path";async function zl(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&ew.win32.isAbsolute(r)?ew.win32.resolve(r):"C:\\Windows",n=ew.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(d,f=!1)=>{s||(s=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=WM(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),zM)}catch{u(!1)}});for(let o=0;o<JM;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var zM,JM,tw=_(()=>{"use strict";zM=1e3,JM=2});function mt(e){return e.replace(GM,"$1 [REDACTED]").replace(UM,"[REDACTED PRIVATE KEY]").replace(KM,"$1[REDACTED]@").replace(YM,"[REDACTED TOKEN]").replace(XM,'$1"[REDACTED]"').replace(QM,"$1$2$1$3$4[REDACTED]$4").replace(ZM,"$1$2[REDACTED]")}var GM,UM,KM,YM,XM,QM,ZM,nn=_(()=>{"use strict";GM=/\b(Bearer|Basic)\s+[^\s"']+/giu,UM=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,KM=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,YM=/\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,XM=/("(?:[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,QM=/(["'])((?:[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,ZM=/\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});import{createWriteStream as eL,promises as tL}from"node:fs";import Rr from"node:path";function TP(e,t){let r=Rr.relative(e,t);return r===""||!Rr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Rr.sep}`)}function jP(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function vh(e,t){if(t.length===0||t.includes("\\")||Rr.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Rr.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Rr.resolve(e),i=Rr.resolve(r,...t.split("/"));if(!TP(r,i))throw new Error("Native check cwd escaped the project root");return i}function Jl(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function rw(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=mt(r);return rL.test(r)&&(t=!0),i})}function la(e,t){if(jP(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return vh(e,t.cwdRef)}async function mo(e){let{plan:t}=e;jP(e.operationId,"Native check operation ID");let r=la(e.projectRoot,t),i=Rr.join(e.runtimeDir,"logs","checks"),n=Rr.join(i,`${e.operationId}-${t.id}.log`);if(!TP(Rr.resolve(e.runtimeDir),Rr.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await tL.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=eL(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Zg(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let u=!1,d=null,f=null,p=Promise.resolve(),v=!1,h=setTimeout(()=>{u=!0,zl(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(h.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{d=m,o.write(`
|
|
202
202
|
[comet] failed to start check: ${mt(m.message)}
|
|
203
|
-
`)}),l.once("close",(m,g)=>{v=!0,clearTimeout(h);let w=(e.now??(()=>new Date))();p.then(()=>{if(f!==null){o.destroy(),c(f);return}o.end(()=>{let S=u||d!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:rw(t.argv),cwdRef:t.cwdRef,status:S?"interrupted":m===0?"passed":"failed",exitCode:m,signal:g,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:Rr.relative(e.runtimeDir,n).split(Rr.sep).join("/")})})})}),o.once("error",m=>{clearTimeout(h),f??=m,v?p.then(()=>c(f)):zl(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let m=l.pid;p=Promise.resolve().then(()=>e.onSpawn({pid:m})).catch(async g=>{f=g,l.exitCode===null&&l.signalCode===null&&await zl(l).catch(()=>l.kill("SIGKILL"))})}})}var rL,gh=_(()=>{"use strict";mh();tw();rn();rL=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});function iw(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function nw(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){iw(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:ut,executionRef:iw(t.executionRef,"Native execution ref"),[$P]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:iw(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[OP]:!0})}})}function wh(e){return typeof e=="object"&&e!==null&&e[OP]===!0}function HP(e){return typeof e=="object"&&e!==null&&e[$P]===!0}var $P,OP,ut,vo=_(()=>{"use strict";$P=Symbol("comet.native.trusted-execution-identity"),OP=Symbol("comet.native.trusted-verifier-envelope"),ut="skill-coordinated"});function yh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Gl(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Ul(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function go(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Nh(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=yh(t,`Native Verifier acceptance ${r}`);Gl(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=go(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:go(i.reason,`Native Verifier acceptance ${n} reason`)}})}function iL(e){let t=yh(e,"Native Verifier final result");if(Gl(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Ul(t.iteration,"Native Verifier iteration"),attempt:Ul(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:Nh(t.acceptance),risks:t.risks,summary:go(t.summary,"Native Verifier summary")}}function nL(e,t){let r=yh(e,`Native Verifier check request ${t}`);if(Gl(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=Ul(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:go(r.id,`Native Verifier check request ${t} ID`),name:go(r.name,`Native Verifier check request ${t} name`),executable:go(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:go(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function aw(e){let t=yh(e,"Native Verifier response");if(t.kind==="final-result")return Gl(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:iL(t.result)};if(t.kind==="request-checks"){if(Gl(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Ul(t.iteration,"Native Verifier iteration"),attempt:Ul(t.attempt,"Native Verifier attempt"),checks:t.checks.map(nL)}}throw new Error("Native Verifier response kind is invalid")}function DP(e){if(!wh(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=aw(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");return i.kind==="request-checks"||ow(i.result,r),i}function ow(e,t){Nh(e.acceptance);let r=[...t.acceptanceIds],i=e.acceptance.map(({id:c})=>c),n=i.filter((c,l)=>i.indexOf(c)!==l),a=i.filter(c=>!r.includes(c)),o=r.filter(c=>!i.includes(c));if(n.length>0||a.length>0||o.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(n)].join(", ")||"none"}; unknown: ${a.join(", ")||"none"}; missing: ${o.join(", ")||"none"})`);if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let s=e.acceptance.map(({result:c})=>c);if(e.verdict==="pass"&&s.some(c=>c!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!s.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!s.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion")}var Kl=_(()=>{"use strict";vo()});import bh from"node:path";function BP(...e){if(e.length===0)return bh.resolve();if(bh.win32.isAbsolute(e[0])){let t=bh.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return bh.resolve(...e)}var qP=_(()=>{"use strict"});import{execFileSync as aL}from"node:child_process";import FP from"node:path";function nn(e,t,r={}){let i=r.timeoutMs??oL,n=r.maxBufferBytes??sL;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=FP.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Xg(e,o,a):e,c=FP.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Qg(t);try{return aL(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new sw(e,t,d,{cause:u})}}var oL,sL,sw,kh=_(()=>{"use strict";mh();oL=6e4,sL=8*1024*1024,sw=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr}});import{promises as MP}from"node:fs";import cL from"node:path";async function wo(e){if(e===process.pid&&cw!==null)return cw;let t=await lL(e);return e===process.pid&&t!==null&&(cw=t),t}async function lL(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([MP.readFile(`/proc/${e}/stat`,"utf8"),MP.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32"){let t=process.env.SystemRoot??"C:\\Windows",r=cL.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=nn(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:15e3,maxBufferBytes:4096}).trim();return/^\d+$/u.test(i)?`win32:${i}`:null}if(process.platform==="darwin"){let t=nn("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}async function Ds(e,t){if(!Number.isSafeInteger(e)||e<=0)return!0;try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return!1}if(!t)return!0;let r=await wo(e);return r===null||r===t}var cw,lw=_(()=>{"use strict";kh();cw=null});import{promises as Yl}from"node:fs";import qt from"node:path";function uw(e,t){let r=qt.normalize(e),i=qt.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function WP(e,t){let r=qt.relative(e,t);return r===""||!qt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qt.sep}`)}function LP(e){return JSON.stringify(e.native)}async function Sh(e,t){let r=await X(e);if(r&&t){if(LP(r)!==LP(t))throw new Error(`Native worktree configuration differs from the source project: ${qt.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Nr(e,t),await ph(e),!0):!1}async function uL(e,t){if(!WP(e,t))return!1;let i=`/${qt.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=A(e,["rev-parse","--git-common-dir"]),a=qt.resolve(e,n),o=qt.join(a,"info","exclude"),s="";try{s=await Yl.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Yl.mkdir(qt.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
203
|
+
`)}),l.once("close",(m,g)=>{v=!0,clearTimeout(h);let w=(e.now??(()=>new Date))();p.then(()=>{if(f!==null){o.destroy(),c(f);return}o.end(()=>{let S=u||d!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:rw(t.argv),cwdRef:t.cwdRef,status:S?"interrupted":m===0?"passed":"failed",exitCode:m,signal:g,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:Rr.relative(e.runtimeDir,n).split(Rr.sep).join("/")})})})}),o.once("error",m=>{clearTimeout(h),f??=m,v?p.then(()=>c(f)):zl(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let m=l.pid;p=Promise.resolve().then(()=>e.onSpawn({pid:m})).catch(async g=>{f=g,l.exitCode===null&&l.signalCode===null&&await zl(l).catch(()=>l.kill("SIGKILL"))})}})}var rL,gh=_(()=>{"use strict";mh();tw();nn();rL=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});function iw(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function nw(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){iw(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:ut,executionRef:iw(t.executionRef,"Native execution ref"),[$P]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:iw(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[OP]:!0})}})}function wh(e){return typeof e=="object"&&e!==null&&e[OP]===!0}function HP(e){return typeof e=="object"&&e!==null&&e[$P]===!0}var $P,OP,ut,vo=_(()=>{"use strict";$P=Symbol("comet.native.trusted-execution-identity"),OP=Symbol("comet.native.trusted-verifier-envelope"),ut="skill-coordinated"});function yh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Gl(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Ul(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function go(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Nh(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=yh(t,`Native Verifier acceptance ${r}`);Gl(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=go(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:go(i.reason,`Native Verifier acceptance ${n} reason`)}})}function iL(e){let t=yh(e,"Native Verifier final result");if(Gl(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Ul(t.iteration,"Native Verifier iteration"),attempt:Ul(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:Nh(t.acceptance),risks:t.risks,summary:go(t.summary,"Native Verifier summary")}}function nL(e,t){let r=yh(e,`Native Verifier check request ${t}`);if(Gl(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=Ul(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:go(r.id,`Native Verifier check request ${t} ID`),name:go(r.name,`Native Verifier check request ${t} name`),executable:go(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:go(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function aw(e){let t=yh(e,"Native Verifier response");if(t.kind==="final-result")return Gl(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:iL(t.result)};if(t.kind==="request-checks"){if(Gl(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Ul(t.iteration,"Native Verifier iteration"),attempt:Ul(t.attempt,"Native Verifier attempt"),checks:t.checks.map(nL)}}throw new Error("Native Verifier response kind is invalid")}function DP(e){if(!wh(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=aw(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");return i.kind==="request-checks"||ow(i.result,r),i}function ow(e,t){Nh(e.acceptance);let r=[...t.acceptanceIds],i=e.acceptance.map(({id:c})=>c),n=i.filter((c,l)=>i.indexOf(c)!==l),a=i.filter(c=>!r.includes(c)),o=r.filter(c=>!i.includes(c));if(n.length>0||a.length>0||o.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(n)].join(", ")||"none"}; unknown: ${a.join(", ")||"none"}; missing: ${o.join(", ")||"none"})`);if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let s=e.acceptance.map(({result:c})=>c);if(e.verdict==="pass"&&s.some(c=>c!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!s.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!s.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion")}var Kl=_(()=>{"use strict";vo()});import bh from"node:path";function BP(...e){if(e.length===0)return bh.resolve();if(bh.win32.isAbsolute(e[0])){let t=bh.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return bh.resolve(...e)}var qP=_(()=>{"use strict"});import{execFileSync as aL}from"node:child_process";import FP from"node:path";function an(e,t,r={}){let i=r.timeoutMs??oL,n=r.maxBufferBytes??sL;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=FP.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Xg(e,o,a):e,c=FP.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Qg(t);try{return aL(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new sw(e,t,d,{cause:u})}}var oL,sL,sw,kh=_(()=>{"use strict";mh();oL=6e4,sL=8*1024*1024,sw=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr}});import{promises as MP}from"node:fs";import cL from"node:path";async function wo(e){if(e===process.pid&&cw!==null)return cw;let t=await lL(e);return e===process.pid&&t!==null&&(cw=t),t}async function lL(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([MP.readFile(`/proc/${e}/stat`,"utf8"),MP.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32"){let t=process.env.SystemRoot??"C:\\Windows",r=cL.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=an(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:15e3,maxBufferBytes:4096}).trim();return/^\d+$/u.test(i)?`win32:${i}`:null}if(process.platform==="darwin"){let t=an("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}async function Ds(e,t){if(!Number.isSafeInteger(e)||e<=0)return!0;try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return!1}if(!t)return!0;let r=await wo(e);return r===null||r===t}var cw,lw=_(()=>{"use strict";kh();cw=null});import{promises as Yl}from"node:fs";import qt from"node:path";function uw(e,t){let r=qt.normalize(e),i=qt.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function WP(e,t){let r=qt.relative(e,t);return r===""||!qt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qt.sep}`)}function LP(e){return JSON.stringify(e.native)}async function Sh(e,t){let r=await X(e);if(r&&t){if(LP(r)!==LP(t))throw new Error(`Native worktree configuration differs from the source project: ${qt.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Nr(e,t),await ph(e),!0):!1}async function uL(e,t){if(!WP(e,t))return!1;let i=`/${qt.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=A(e,["rev-parse","--git-common-dir"]),a=qt.resolve(e,n),o=qt.join(a,"info","exclude"),s="";try{s=await Yl.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Yl.mkdir(qt.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
204
204
|
`)?"":`
|
|
205
205
|
`;return await Yl.appendFile(o,`${c}${i}
|
|
206
|
-
`,"utf8"),!0}function dL(e,t,r){let i=qt.resolve(e,r??qt.join(".worktrees",t)),n=qt.resolve(e,A(e,["rev-parse","--git-common-dir"]));if(WP(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(kt(e).some(a=>uw(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function fL(e){try{throw await Yl.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function VP(e){try{return await Yl.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xl(e){let t=qt.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ne(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await pe(t,e.sourceConfig?.native.artifact_root??"docs");return Xa([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=ne(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Gg(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Gg(t,o),!An(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!PP(t))throw new Error("Native branch isolation requires a clean current working directory");if(An(t,n))throw new Error(`Native change branch already exists: ${n}`);A(t,["switch","-c",n,o]),p=!0}let v;try{v=await Sh(t,e.sourceConfig)}catch(h){throw new ua(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?qt.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!uw(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Sh(t,e.sourceConfig)}catch(h){throw new ua(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=td(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await VP(c.root)){let p=e.worktreePath?qt.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!uw(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Sh(c.root,e.sourceConfig)}catch(h){throw new ua(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await VP(c.root)&&(A(i.primaryWorktreeRoot,["worktree","prune"]),s=td(i.primaryWorktreeRoot));let l=An(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=dL(i.primaryWorktreeRoot,e.name,e.worktreePath);await fL(u);let d=await uL(i.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{A(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Sh(u,e.sourceConfig)}catch(p){throw new ua(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var ua,Eh=_(()=>{"use strict";
|
|
206
|
+
`,"utf8"),!0}function dL(e,t,r){let i=qt.resolve(e,r??qt.join(".worktrees",t)),n=qt.resolve(e,A(e,["rev-parse","--git-common-dir"]));if(WP(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(kt(e).some(a=>uw(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function fL(e){try{throw await Yl.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function VP(e){try{return await Yl.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xl(e){let t=qt.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ne(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await pe(t,e.sourceConfig?.native.artifact_root??"docs");return Xa([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=ne(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Gg(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Gg(t,o),!An(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!PP(t))throw new Error("Native branch isolation requires a clean current working directory");if(An(t,n))throw new Error(`Native change branch already exists: ${n}`);A(t,["switch","-c",n,o]),p=!0}let v;try{v=await Sh(t,e.sourceConfig)}catch(h){throw new ua(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?qt.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!uw(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Sh(t,e.sourceConfig)}catch(h){throw new ua(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=td(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await VP(c.root)){let p=e.worktreePath?qt.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!uw(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Sh(c.root,e.sourceConfig)}catch(h){throw new ua(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await VP(c.root)&&(A(i.primaryWorktreeRoot,["worktree","prune"]),s=td(i.primaryWorktreeRoot));let l=An(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=dL(i.primaryWorktreeRoot,e.name,e.worktreePath);await fL(u);let d=await uL(i.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{A(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Sh(u,e.sourceConfig)}catch(p){throw new ua(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:f}})}var ua,Eh=_(()=>{"use strict";rn();zt();tt();ho();Qa();Q();ua=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import{createHash as QP}from"node:crypto";import zP from"path";function Ft(e,t){return e<t?-1:e>t?1:0}function fw(e){if(!mw.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function wL(e,t){return e===t?0:e===null?-1:t===null?1:Ft(e,t)}function fa(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=zP.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||zP.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function tC(e,t){return e==="."?e:fa(e,t)}function Bs(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function yL(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:fa(e.path,`${t} path`),hash:e.hash,size:Bs(e.size,`${t} size`),type:"file"}}function NL(e,t){return{path:tC(e.path,`${t} path`),size:e.size===null?null:Bs(e.size,`${t} size`),type:e.type,reason:e.reason}}function bL(e,t){return Ft(e.path,t.path)||Ft(e.hash,t.hash)||e.size-t.size}function kL(e,t){return Ft(e.path,t.path)||Ft(e.reason,t.reason)||Ft(e.type,t.type)||(e.size??-1)-(t.size??-1)}function eu(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
207
207
|
`,"utf8")}function da(e,t,r){let i=`${t}
|
|
208
208
|
${dl(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function SL(e){if(eu(e)<=No)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=QP("sha256");a.update(`${mL}
|
|
209
|
-
`),e.omissionOverflow&&da(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(i+=1),n+=1,da(a,"omission",f)},s=f=>{i+=1,n+=1,da(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let p=r[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(f,1),p}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;eu(u)>No;){if(r.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(r.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function hw(e){let t=
|
|
210
|
-
`);let r=0;vw(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){da(t,"change",n);let a=0;for(let o of e.declaredArtifacts)ru(o,n.path)&&(a+=1,da(t,"change-attribution",o));da(t,"change-end",{attributionCount:a}),a===0&&da(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&da(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function sC(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=CL(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let P=new Set(r.externalDrift.paths),b=new Set(o.changePaths),k=r.externalDrift.paths.filter(R=>!b.has(R)||n.some(I=>ru(I,R)));if(k.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${k.slice(0,8).join(", ")}`);if(P.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(Ql,e),c=D(Ql,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[P,b]of[["baseline",e],["current",t]])for(let k of b.omitted){if(l.length>=gL)break;l.push(an({kind:"snapshot-omission",source:P,path:k.path,evidence:{reason:k.reason,size:k.size,type:k.type}},`${P} snapshot omitted ${k.path}: ${k.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...GP("baseline",e),...GP("current",t),...o.totalChanges===0&&a===null?[an({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")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let P=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(b=>P.has(b)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(b=>!P.has(b))}},v=P=>{let b=o.candidates.slice(0,P.detailedChangeCount),k=b.filter(Ke=>Ke.attributedTo.length===0&&!u.has(Ke.path)),R=o.totalChanges-b.length,I=o.totalUnattributed-k.length,C=d-P.detailedOmissionCount,Ne=I+C,oe=[...k.map(Ke=>an({kind:"unattributed-change",source:"implementation-scope",path:Ke.path,evidence:{after:Ke.after,before:Ke.before,changeKind:Ke.kind}},`Changed path is not covered by a declared artifact: ${Ke.path}`)),...l.slice(0,P.detailedOmissionCount),...f,...Ne>0?[oC(P.overflowHash,{changes:R,unattributed:I,unresolved:Ne})]:[]],ce=RL(oe),Ue=P.includeGitAdvisory?p():void 0;return{schema:dw,contractHash:i,baselineProjectionRef:fw(s),baselineProjectionHash:s,currentProjectionRef:fw(c),currentProjectionHash:c,complete:ce.length===0,declaredArtifacts:n,changes:b,unattributed:k,unresolvedScopes:ce,noCodeReason:a,...Ue?{gitAdvisory:Ue}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,m=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let P=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:w});if(eu({...P,scopeHash:w})<=No)break;if(g){g=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>m?AL({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):w,y=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:N}),E={...y,scopeHash:D(eC,y)};if(eu(E)>No)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function Fs(e){let t=hw(e.baseline),r=hw(e.current),i=aC(e);return{authority:i,baseline:t,current:r,scope:sC(t,r,i)}}function _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ii(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function yo(e,t){if(typeof e!="string"||!mw.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function KP(e,t,r){let i=fw(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function qs(e,t){let r=_i(e,"Native snapshot projection");if(Ii(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==ZP)throw new Error("Native snapshot projection schema is invalid");let i=Qi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=hw(i);if(D(Ql,r)!==D(Ql,n))throw new Error("Native snapshot projection is not canonical");let a=D(Ql,n);if(t!==void 0&&yo(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function gw(e,t){let r=_i(e,`Declared artifact ${t}`);if(Ii(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:fa(r.path,`Declared artifact ${t} path`),kind:r.kind}}function YP(e,t){if(e===null)return null;let r=_i(e,t);return Ii(r,["hash","size"],[],t),{hash:yo(r.hash,`${t} hash`),size:Bs(r.size,`${t} size`)}}function XP(e,t){let r=_i(e,`Implementation change ${t}`);if(Ii(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(gw),n=tu(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=YP(r.before,`Implementation change ${t} before`),o=YP(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:fa(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function IL(e,t){let r=_i(e,`Unresolved scope ${t}`);Ii(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?tC(r.path,`Unresolved scope ${t} path`):fa(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Zl(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>fa(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ft);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function cC(e){let t=_i(e,"Native implementation external drift");if(Ii(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Zl(t.paths,"Native external drift paths");return nC({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Ms(e){let t=_i(e,"Native implementation scope"),r=[..._L].filter(k=>k!=="gitAdvisory"&&k!=="externalDrift");if(Ii(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==dw)throw new Error("Native implementation scope schema is invalid");let i=yo(t.contractHash,"Implementation scope contractHash"),n=yo(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=KP(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=yo(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=KP(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(gw);if(JSON.stringify(c)!==JSON.stringify(tu(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(XP),u=[...l].sort((k,R)=>Ft(k.path,R.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(k=>k.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(k=>`${k.kind}:${k.path}`));if(l.some(k=>k.attributedTo.some(R=>!d.has(`${R.kind}:${R.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(k=>JSON.stringify(k.attributedTo)!==JSON.stringify(c.filter(R=>ru(R,k.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(XP),p=t.externalDrift===void 0?void 0:cC(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(k=>k.attributedTo.length===0&&!v.has(k.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(IL),g=m.filter(k=>k.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:xL(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...h.map(k=>an({kind:"unattributed-change",source:"implementation-scope",path:k.path,evidence:{after:k.after,before:k.before,changeKind:k.kind}},`Changed path is not covered by a declared artifact: ${k.path}`)),...l.length+(w?.changes??0)===0&&S===null?[an({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],y=m.filter(k=>k.kind==="unattributed-change"||k.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(pw))||new Set(m.map(k=>k.id)).size!==m.length||JSON.stringify(y)!==JSON.stringify(N.sort(pw))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let E;if(t.gitAdvisory!==void 0){let k=_i(t.gitAdvisory,"Implementation scope Git advisory");if(Ii(k,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),k.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let R=Zl(k.changedPaths,"Git changed paths"),I=Zl(k.pathsPresentInSnapshotChanges,"Git present paths"),C=Zl(k.pathsAbsentFromSnapshotChanges,"Git absent paths"),Ne=[...I,...C].sort(Ft);if(JSON.stringify(Ne)!==JSON.stringify(R)||C.some(oe=>l.some(ce=>ce.path===oe)))throw new Error("Implementation scope Git advisory partition is invalid");E={advisoryOnly:!0,changedPaths:R,pathsPresentInSnapshotChanges:I,pathsAbsentFromSnapshotChanges:C}}let P={schema:dw,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...E?{gitAdvisory:E}:{},...p?{externalDrift:p}:{}},b=yo(t.scopeHash,"Implementation scope scopeHash");if(D(eC,P)!==b)throw new Error("Implementation scope content hash mismatch");return{...P,scopeHash:b}}function TL(e){let t=_i(e,"Native implementation scope authority");if(Ii(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(gw);if(JSON.stringify(r)!==JSON.stringify(tu(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=Zl(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:cC(t.externalDrift),a=aC({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Ls(e){let t=_i(e,"Native implementation scope bundle");Ii(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=TL(t.authority),i=qs(t.baseline),n=qs(t.current),a=Ms(t.scope),o=sC(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function lC(e){let t=Ms(e.scope);return Ls({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var dw,ZP,Ql,eC,hL,pL,mL,mw,No,vL,gL,_L,on=_(()=>{"use strict";ct();na();dw="comet.native.implementation-scope.v2",ZP="comet.native.content-snapshot-projection.v1",Ql="comet.native.content-snapshot-projection.v1",eC="comet.native.implementation-scope.v2",hL="comet.native.unresolved-scope-id.v1",pL="comet.native.scope-detail-overflow.v1",mL="comet.native.snapshot-projection-overflow.v2",mw=/^[a-f0-9]{64}$/u,No=1024*1024,vL=128,gL=128;_L=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import uC from"node:path";function sn(e,t){if(!fC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function pC(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function ww(e,t,r=2e3){let i=mt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function iu(e,t){let r=uC.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||uC.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function HL(e,t,r){let i=iu(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=yi(i),a=i.toLowerCase(),o=r?iu(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function yw(e){let t=iu(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Vs(e,t){return e<t?-1:e>t?1:0}function Rh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ph(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function mC(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function dC(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function DL(e){let t=Rh(e,"Native acceptance trace");if(Ph(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!fC.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=iu(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Rh(o,`Native acceptance trace entry ${s}`);if(Ph(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>yw(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Vs))||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:iu(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:ww(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Vs(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=sn(t.traceHash,"Native acceptance trace hash");if(D(jL,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Ch(e){let t=Rh(e,"Native partial allowance");if(Ph(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Vs))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:pC(t.change),scopeHash:sn(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:ww(t.reason,"Partial allowance reason"),confirmedSummary:ww(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:hC(t.sourceRevision),confirmedAt:mC(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=sn(t.allowanceHash,"Native partial allowance hash");if(D($L,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function nu(e){let t=Rh(e,"Native verification evidence");if(Ph(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=sn(t.implementationScopeHash,"Native verification implementation scope hash"),i=DL(t.acceptanceTrace),n=sn(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:sn(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>yw(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Vs)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(Vs);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>yw(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Vs)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:pC(t.change),sourceRevision:hC(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:sn(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:dC(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:HL(t.reportRef,"Native verification report ref"),reportHash:sn(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:dC(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:mC(t.createdAt,"Native verification timestamp")},d=sn(t.envelopeHash,"Native verification envelope hash");if(D(OL,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var fC,jL,$L,OL,au=_(()=>{"use strict";ct();rn();Nc();on();fC=/^[a-f0-9]{64}$/u,jL="comet.native.acceptance-trace.v2",$L="comet.native.partial-allowance.v1",OL="comet.native.verification-evidence.v2"});import vC from"node:path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ma(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function cn(e,t){if(typeof e!="string"||!BL.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function bC(e,t){let r=Pr(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function wC(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function zL(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>LL||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=vC.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||vC.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function JL(e){let t=pa(e,"Native check receipt checker");ma(t,["policy","version","hash","limits"],"Native check receipt checker");let r=pa(t.limits,"Native check receipt limits");if(ma(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ha||t.version!==ou||t.hash!==Ah||r.maxFiles!==Te.maxFiles||r.maxFileBytes!==Te.maxFileBytes||r.maxTotalBytes!==Te.maxTotalBytes||r.maxIssues!==Te.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ha,version:ou,hash:Ah,limits:{...Te}}}function GL(e){let t=pa(e,"Native check receipt contract");return ma(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:cn(t.expectedHash,"Native check expected contract hash"),beforeHash:cn(t.beforeHash,"Native check before contract hash"),afterHash:cn(t.afterHash,"Native check after contract hash")}}function UL(e){let t=pa(e,"Native check receipt implementation");return ma(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:cn(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:cn(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:cn(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:cn(t.afterSnapshotHash,"Native check after snapshot hash")}}function KL(e,t){let r=pa(e,`Native check batch ${t}`);ma(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Pr(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Pr(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Pr(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Pr(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Pr(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Pr(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>Te.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>Te.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function YL(e){let t=pa(e,"Native check receipt counts");ma(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Pr(t.filesSelected,"Native check filesSelected"),filesScanned:Pr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Pr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Pr(t.bytesScanned,"Native check bytesScanned"),issueCount:Pr(t.issueCount,"Native check issueCount"),recordedIssueCount:Pr(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(KL):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>Te.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>Te.maxFiles||r.bytesScanned>Te.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function XL(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||gC.indexOf(e.kind)-gC.indexOf(t.kind)}function QL(e){if(!Array.isArray(e)||e.length>Te.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=pa(i,`Native check issue ${n}`);if(ma(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!VL.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:zL(a.path,`Native check issue ${n} path`),line:bC(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(XL);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function ZL(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!WL.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=NC.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function kC(e){return D(ML,e)}function ln(e){let t=pa(e,"Native check receipt");if(ma(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==xh)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!qL.test(t.change))throw new Error("Native check receipt change name is invalid");let r=bC(t.sourceRevision,"Native check source revision"),i=JL(t.checker),n=GL(t.contract),a=UL(t.implementation),o=kC({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(cn(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=wC(t.startedAt,"Native check receipt startedAt"),c=wC(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=YL(t.counts),u=QL(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=ZL(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>Te.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>Te.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:xh,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=cn(t.receiptHash,"Native check receipt content hash");if(D(yC,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}function SC(e){let t={policy:ha,version:ou,hash:Ah,limits:{...Te}},r={schema:xh,...e,checker:t,inputHash:kC({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return ln({...r,receiptHash:D(yC,r)})}var xh,yC,ha,ou,Te,BL,qL,FL,ML,LL,Ah,VL,gC,NC,WL,Ws=_(()=>{"use strict";ct();xh="comet.native.check-receipt.v1",yC="comet.native.check-receipt.v1",ha="scoped-text-safety",ou=1,Te=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),BL=/^[a-f0-9]{64}$/u,qL=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FL="comet.native.checker-policy.v1",ML="comet.native.check-input.v1",LL=2048,Ah=D(FL,{policy:ha,version:ou,limits:Te,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),VL=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),gC=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],NC=["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"],WL=new Set(NC)});function zs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function va(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function un(e,t){if(typeof e!="string"||!tV.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function li(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=mt(e).trim();if(!r||r.length>aV||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Nw(e,t){let r=li(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function su(e,t,r=li,i=!1,n=oV){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function cV(e,t){if(typeof e!="string"||!rV.test(e))throw new Error(`${t} is invalid`);return e}function lV(e){let t=zs(e,"Native verification receipt bindings");if(va(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!iV.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:un(t.contractHash,"Native verification receipt contract hash"),scopeHash:un(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:un(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:un(t.artifactHash,"Native verification receipt artifact hash")}}function uV(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=nV.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function dV(e,t,r,i){let n=zs(t,`Native ${e} evidence`);if(e==="automated-check"){if(va(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Nw(n.startedAt,"Native automated-check start time"),o=Nw(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=zs(n.worktree,"Native automated-check worktree");if(va(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=zs(n.afterFence,"Native automated-check after fence");if(va(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:li(n.executable,"Native automated-check executable"),args:su(n.args,"Native automated-check arguments",li,!0),cwd:li(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:li(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:un(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:un(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:un(n.outputHash,"Native automated-check output hash"),outputSummary:li(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){va(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=uV(n.checkReceiptRef);if(un(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:su(n.subjects,"Native static inspection subjects",li,i==="required-check"),rule:li(n.rule,"Native static inspection rule"),resultSummary:li(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return va(n,["steps","observations"],"Native manual-evidence evidence"),{steps:su(n.steps,"Native manual evidence steps"),observations:su(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function RC(e){let t=zs(e,"Native verification receipt");if(va(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=li(t.actor,"Native verification receipt actor"),o=su(t.acceptanceIds,"Native receipt acceptance IDs",cV,i==="required-check",sV).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:_h,kind:r,role:i,status:n,bindings:lV(t.bindings),acceptanceIds:o,actor:a,issuedAt:Nw(t.issuedAt,"Native verification receipt issue time"),evidence:dV(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ha||s.actor!==`native-runtime:${ha}`))throw new Error("Native required check policy identity is invalid");return s}function PC(e){let t=RC({schema:_h,...e});return{...t,receiptHash:D(EC,t)}}function cu(e){let t=zs(e,"Native verification receipt");if(va(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==_h)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=RC(i),a=un(t.receiptHash,"Native verification receipt hash");if(D(EC,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Ih(e){return D(eV,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var _h,EC,eV,tV,rV,iV,nV,aV,oV,sV,Js=_(()=>{"use strict";ct();Ws();rn();_h="comet.native.verification-receipt.v3",EC=_h,eV="comet.native.declared-artifacts.v1",tV=/^[a-f0-9]{64}$/u,rV=/^acceptance-[a-f0-9]{64}$/u,iV=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nV=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,aV=4096,oV=256,sV=1024});var $C={};ed($C,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>Wr,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>fV,listNativeVerificationReceiptRefs:()=>xw,nativeEvidenceRef:()=>di,nativeReportEvidenceRef:()=>kw,readArchivedNativeVerificationAcceptanceCounts:()=>kV,readNativeImplementationScope:()=>Us,readNativeImplementationScopeBundle:()=>dn,readNativePartialAllowance:()=>du,readNativeVerificationEvidence:()=>Ro,readNativeVerificationReceipt:()=>Eo,readNativeVerificationReportSnapshot:()=>uu,removeNativeVerificationReportSnapshot:()=>Sw,writeNativeImplementationScope:()=>NV,writeNativePartialAllowance:()=>bV,writeNativeVerificationEvidence:()=>jC,writeNativeVerificationReceipt:()=>Cw,writeNativeVerificationReportSnapshot:()=>Gs});import{createHash as _C}from"node:crypto";import{promises as er}from"node:fs";import ui from"node:path";function bw(e,t){let r=ui.relative(e,t);return r===""||!ui.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ui.sep}`)}function hV(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lu(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function CC(e){let t=await er.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await er.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function pV(e,t){let r=ui.resolve(e),i=ui.resolve(t);if(!bw(r,i))throw new Error("Native evidence path is outside its change");let n=[await CC(r)],a=r;for(let o of ui.relative(r,i).split(ui.sep).filter(Boolean)){a=ui.join(a,o);let s=await CC(a);if(!bw(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function xC(e){for(let t of e){let r=await er.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hV(t,r)||await er.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function mV(e,t,r={}){let i=await pV(t,ui.dirname(e));await r.afterParentChainCaptured?.();let n=await er.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await er.realpath(e);if(!bw(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await er.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),er.lstat(e),er.realpath(e)]);if(await xC(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!lu(s,n)||!lu(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Wr)throw new Error(`Native evidence document exceeds ${Wr} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Wr+1-d,g=await o.read(f,0,Math.min(f.length,m),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>Wr)throw new Error(`Native evidence document exceeds ${Wr} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),er.lstat(e),er.realpath(e)]);if(await xC(i),!v.isFile()||v.isSymbolicLink()||h!==a||!lu(s,p)||!lu(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function di(e,t){if(!IC.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function kw(e){return di("reports",e)}async function Gs(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Wr||_C("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return So({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Sw(e){let t=Ew(e.paths,e.name,"reports",e.hash),r=F(e.paths,t);await j(r,t);let i=await er.lstat(t);if(await uu(e.paths,e.name,e.hash),await j(r,t),!lu(i,await er.lstat(t)))throw new Error("Native report evidence changed before rollback");await er.unlink(t)}async function uu(e,t,r,i,n){if(!IC.test(r))throw new Error("Native report evidence hash is invalid");let a=await Ti({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});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!==r||typeof o.content!="string"||_C("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function ko(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function Ew(e,t,r,i,n){let a=di(r,i);return n?ui.join(n,...a.split("/")):Jn(V(e,t),a)}async function Ti(e){let t=Ew(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??F(e.paths,t);return await j(r,t),mV(t,r,e.hooks)}async function So(e){Th(e.value);let t=Ew(e.paths,e.name,e.kind,e.hash),r=F(e.paths,t);await j(r,t);try{let n=await Ti(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return di(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await fe(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Ti(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return di(e.kind,e.hash)}function Th(e){if(vV(e)>Wr)throw new Error(`Native evidence document exceeds ${Wr} bytes`)}function vV(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
211
|
-
`,"utf8")}function AC(e,t){return qs(e,t)}function gV(e,t){let r=Ms(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function TC(e,t,r){let i=Ch(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Rw(e,t,r){let i=nu(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function wV(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function yV(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,d=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(d)||l<0||u<0||d<0||u+d>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:d}}async function Pw(e,t,r,i=!1,n){let a=await Us(e,t,r.implementationScopeRef,void 0,n);if(i&&await uu(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await du(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function NV(e){let t=Ls(e.bundle),{baseline:r,current:i,scope:n}=t;return Th(r),Th(i),Th(n),await So({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await So({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),So({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function dn(e,t,r,i,n){let a=ko(r,"scopes"),o=gV(await Ti({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=ko(o.baselineProjectionRef,"snapshots"),c=ko(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Ti({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>AC(d,s)),Ti({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>AC(d,c))]);return lC({baseline:l,current:u,scope:o})}async function Us(e,t,r,i,n){return(await dn(e,t,r,i,n)).scope}async function bV(e){let t=TC(e.allowance,e.name,e.allowance.allowanceHash),r=await Us(e.paths,e.name,di("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return So({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function du(e,t,r,i,n){let a=ko(r,"allowances");return TC(await Ti({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Cw(e){let t=cu(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return So({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Eo(e,t,r,i,n){let a=ko(r,"receipts"),o=cu(await Ti({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function xw(e,t){let r=ui.join(V(e,t),"evidence","receipts");await j(F(e,r),r);let i;try{i=await er.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>di("receipts",n))}async function jC(e){let t=Rw(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Pw(e.paths,e.name,t,!0),So({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Ro(e,t,r,i,n){let a=ko(r,"verifications"),o=Rw(await Ti({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Pw(e,t,o,!1,n),o}async function kV(e,t,r,i){let n=ko(r,"verifications"),a=await Ti({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=yV(a,t,n);if(o)return o;let s=Rw(a,t,n);return await Pw(e,t,s,!1,i),wV(s.acceptanceTrace)}var IC,Wr,fV,zr=_(()=>{"use strict";$e();Q();Ir();on();au();Js();IC=/^[a-f0-9]{64}$/u,Wr=No,fV=3*Wr});var HC={};ed(HC,{executeNativeSupervisorChecks:()=>Tw,readNativeSupervisorCheckEvidence:()=>jh});import{createHash as SV,randomUUID as EV}from"node:crypto";import{promises as RV}from"node:fs";import OC from"node:path";function Iw(e){return SV("sha256").update(e).digest("hex")}function Aw(e,t){if(A(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||A(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!Er(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function _w(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function Tw(e){if(e.plans.length===0||new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:s})=>!s))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:s,content:c})=>!s.trim()||Buffer.byteLength(c)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=D("comet.native.supervisor-check-plan.v1",{plans:e.plans,materials:e.materials}),r=await $(e.paths,"reserve Supervisor checks",async()=>{let s=await ee(e.paths,e.parent),c=_w(s,e.child,e.runId);Aw(e.parent,c),e.plans.forEach(u=>la(c.projectRoot,u));let l=c.checkExecution;if(l?.status==="running"){let u=await Ds(l.ownerPid,l.ownerIdentity),d=Date.parse(l.expiresAt??"")||Date.parse(l.startedAt)+3e4;if(u){if(!(Date.now()<d))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(l.key!==t)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(c),execute:!1}}let f=l.activeProcess;if(f===void 0||f?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${OC.join(Oe(e.paths,e.parent),"logs","checks")} for operation ${l.operationId}; stop any remaining check process in ${c.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${c.runId}, and dispatch a new Verifier for the preserved candidate.`);if(f&&await Ds(f.pid,f.identity)){if(!(Date.now()<d))throw new Error(`Native Supervisor check ${f.checkId} is still running as PID ${f.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(c),execute:!1}}l.status="interrupted"}return l?.status==="completed"&&l.key===t&&e.plans.every(({repeatable:u})=>u)?{task:structuredClone(c),execute:!1}:(c.checkExecution={operationId:EV(),key:t,status:"running",ownerPid:process.pid,ownerIdentity:await wo(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((u,d)=>u+d.timeoutMs,0)+3e4).toISOString()},c.checksReason="running",s.stateVersion+=1,await ge(e.paths,s),{task:structuredClone(c),execute:!0})}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.receiptRef&&await jh({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=Oe(e.paths,e.parent),o=async s=>{await $(e.paths,"register Supervisor check process",async()=>{let c=await ee(e.paths,e.parent),l=_w(c,e.child,e.runId);if(l.checkExecution?.operationId!==n||l.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");l.checkExecution.activeProcess=s,c.stateVersion+=1,await ge(e.paths,c)})};try{let s=[];for(let d of e.plans){await o({status:"starting",checkId:d.id});let f=await mo({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:d,onSpawn:async({pid:h})=>{await o({status:"running",checkId:d.id,pid:h,identity:await wo(h)??void 0})}});await o(null);let p=OC.join(a,f.logRef),v=await RV.readFile(p,"utf8");s.push({...f,logContent:mt(v).slice(0,128*1024)})}Aw(e.parent,i);let c={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:t,checks:s,materials:e.materials.map(({name:d,content:f})=>{let p=mt(f);return{name:d,content:p,hash:Iw(p)}})},l=JSON.stringify(c),u=await Gs({paths:e.paths,name:e.parent,hash:Iw(l),text:l});return await $(e.paths,"complete Supervisor checks",async()=>{let d=await ee(e.paths,e.parent),f=_w(d,e.child,e.runId);if(f.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Aw(e.parent,f),f.checkExecution.status="completed",f.checkExecution.receiptRef=u,f.checksReason="completed",d.stateVersion+=1,await ge(e.paths,d)}),{status:"completed",operationId:n,receiptRef:u}}catch(s){throw await $(e.paths,"interrupt Supervisor checks",async()=>{let c=await ee(e.paths,e.parent),l=c?.children.find(({name:u})=>u===e.child)?.task;l?.runId===e.runId&&l.checkExecution?.operationId===n&&(l.checkExecution.status="interrupted",l.checksReason="not-run",c.stateVersion+=1,await ge(e.paths,c))}),s}}async function jh(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await uu(e.paths,e.parent,t[1])),i=e.task;if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!Array.isArray(r.materials)||r.materials.some(({content:n,hash:a})=>Iw(n)!==a))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var jw=_(()=>{"use strict";ho();tn();lw();ct();gh();zr();it();Q();rn();fn()});import Ae from"node:path";import{randomUUID as MC}from"node:crypto";import{promises as Oh}from"node:fs";function CV(e,t){let r=Ae.relative(Ae.resolve(e),Ae.resolve(t));return r===""||!Ae.isAbsolute(r)&&!r.startsWith(`..${Ae.sep}`)}function LC(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function xV(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return BP(e,".worktrees",`${t}-${r}`)}async function VC(e){let t=Ae.join(".worktrees",`${e.parent}-integration`);return Xl({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:LC(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function AV(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Xl({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Ae.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function WC(e,t){return Ae.join(Oe(e,t),"supervisor")}function Ys(e,t){return Ae.join(WC(e,t),"state.json")}function zC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Ow)throw new Error(`Native Supervisor state schema must be ${Ow}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(ji(t.integration.targetCommit,"Native Supervisor target commit"),ji(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");ji(n.candidateCommit,"Native Supervisor integration candidate commit"),ji(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&ji(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(ji(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function ee(e,t,r={}){try{let i=await Oh.readFile(Ys(e,t),"utf8"),n=JSON.parse(i);if(zC(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(ga(),ZC)),{readNativePortableState:l}=await Promise.resolve().then(()=>(ai(),ng)),u=await l(Ae.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:Ae.join(o.changesDir,t),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:p})=>p===f.name)&&(f.acceptanceScope=$h(d.contract,f.name),f.contractHash=D("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(ai(),ng)),s=await o(Ae.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ge(e,t){zC(t),await Oh.mkdir(e.changesRuntimeDir,{recursive:!0}),await fe(Ys(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function ji(e,t){if(!PV.test(e))throw new Error(`${t} must be a Git commit`)}function dr(e){return structuredClone(e)}function fi(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function _V(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function IV(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Hw(e){ji(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:$h(e.contract,i.name),contractHash:D("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ow,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function $h(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Hh(e){let t=LC(e.parent),r=wi(e.paths.projectRoot,t);if(!r)return null;let i=wi(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=kt(e.paths.projectRoot).map(o=>Ae.resolve(o)).find(o=>ne(o).currentBranch===t);if(!n)return null;let a=Hw({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return fi(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function JC(e){let t=dr(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=$h(e.contract,n.name),s=D("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.status=n.candidateCommit?"needs-reverify":"ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."),n.acceptanceScope=o,n.contractHash=s}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:$h(e.contract,n.name),contractHash:D("comet.native.supervisor-contract.v1",e.contract)});return t.stateVersion+=1,t}function Dw(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=dr(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);_V(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,fi(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function TV(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function GC(e,t){let r=TV(e,t),i=dr(e);return fi(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function jV(e,t,r){let i=ne(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!Er(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=A(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return A(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return A(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(A(e,["merge","--ff-only",r]),A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function Ks(e){if(!Er(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=A(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Ae.resolve(t)!==Ae.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=A(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return A(e.integration.worktree,["rev-parse","HEAD"])}function $V(e,t,r){let i=ne(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!Er(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function Bw(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,fi(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Dh(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,fi(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function UC(e){return $(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await ee(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await X(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let d;try{d=await AV({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?$V(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):jV(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let v=dr(o),h=v.children.find(({name:m})=>m===l.name);h&&(h.blocker=p.message,fi(v,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let f=Dw(o,{role:u?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:MC()});o=f.state,s.push(f.task)}return(s.length>0||c)&&await ge(e.paths,o),{state:o,tasks:s}})}function KC(e,t){ji(t.candidateCommit,"Native Supervisor candidate commit");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,fi(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function YC(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return ow({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),fi(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function DC(e,t){ji(t.integrationCommit,"Native Supervisor integration commit");let r=dr(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,fi(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function XC(e){let t=await $(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let d=await ee(e.paths,e.state.parent)??e.state,f=d.integration.checkExecution;if(f?.status==="running"){if(await Ds(f.ownerPid,f.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(f.activeProcess===void 0||f.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(f.activeProcess&&await Ds(f.activeProcess.pid,f.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(d.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let p=d.children.find(({name:w})=>w===e.name);if(!p)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=IV(d).find(({status:w})=>w!=="integrated"&&w!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(p.status!=="verified"||!p.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:N})=>!N))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:N})=>N)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(e.checkPlans.forEach(N=>la(d.integration.worktree,N)),!p.verification?.receiptRef||!p.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:w}=await Promise.resolve().then(()=>(jw(),HC)),S=await w({paths:e.paths,parent:d.parent,task:p.verification.execution,receiptRef:p.verification.receiptRef});if(S.candidateCommit!==p.verifiedCommit||S.checks.some(({status:N})=>N!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let h=Ks(d);if(h!==d.integration.headCommit){let w=(()=>{try{return A(d.integration.worktree,["merge-base","--is-ancestor",d.integration.headCommit,h]),!0}catch{return!1}})(),S=(()=>{try{return A(d.integration.worktree,["merge-base","--is-ancestor",p.verifiedCommit,h]),!0}catch{return!1}})();if(!w||!S)throw new Error(`Native Supervisor integration head drifted: expected ${d.integration.headCommit}, got ${h}`)}try{A(d.integration.worktree,["cat-file","-e",`${p.verifiedCommit}^{commit}`])}catch(w){throw new Error(`Native Supervisor verified commit is unavailable: ${p.verifiedCommit}`,{cause:w})}if(h===d.integration.headCommit){try{A(d.integration.worktree,["merge","--no-ff","--no-edit",p.verifiedCommit])}catch(w){throw new Error(`Native Supervisor integration conflict preserved in ${d.integration.worktree}`,{cause:w})}h=A(d.integration.worktree,["rev-parse","HEAD"])}let m=h;if(e.checkPlans){let w=MC(),S=D("comet.native.supervisor-integration-plan.v1",{child:e.name,candidateCommit:p.verifiedCommit,integrationCommit:m,plans:e.checkPlans});return d.integration.checkExecution={operationId:w,key:S,child:e.name,candidateCommit:p.verifiedCommit,integrationCommit:m,status:"running",ownerPid:process.pid,ownerIdentity:await wo(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null},d.stateVersion+=1,await ge(e.paths,d),{pending:{state:d,candidateCommit:p.verifiedCommit,integrationCommit:m,operationId:w,key:S}}}let g=DC(d,{name:e.name,integrationCommit:m,checks:e.checks});return await ge(e.paths,g),{completed:g}});if(t.completed)return t.completed;let{state:r,candidateCommit:i,integrationCommit:n,operationId:a,key:o}=t.pending,{writeNativeVerificationReportSnapshot:s}=await Promise.resolve().then(()=>(zr(),$C)),{createHash:c}=await import("node:crypto"),l=async u=>$(e.paths,"record Supervisor integration check process",async()=>{let d=await ee(e.paths,r.parent),f=d?.integration.checkExecution;if(!d||f?.operationId!==a||f.key!==o||f.status!=="running")throw new Error("Native Supervisor integration check operation is stale");f.activeProcess=u,d.stateVersion+=1,await ge(e.paths,d)});try{let u=[];for(let h of e.checkPlans)await l({status:"starting",checkId:h.id}),u.push(await mo({projectRoot:r.integration.worktree,runtimeDir:Oe(e.paths,r.parent),operationId:a,plan:h,onSpawn:async({pid:m})=>l({status:"running",checkId:h.id,pid:m,identity:await wo(m)??void 0})})),await l(null);let d=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:r.parent,child:e.name,candidateCommit:i,integrationCommit:n,operationId:a,planHash:o,results:u}),f=await s({paths:e.paths,name:r.parent,hash:c("sha256").update(d).digest("hex"),text:d}),p=u.map(h=>({name:h.name,status:h.status==="interrupted"?"incomplete":h.status,reason:h.status==="passed"?null:h.timedOut?"timed out":`exit ${h.exitCode??h.signal??"interrupted"}`,receiptRef:f})),v=p.filter(({status:h})=>h!=="passed");return await $(e.paths,"complete Supervisor integration checks",async()=>{let h=await ee(e.paths,r.parent),m=h?.children.find(({name:S})=>S===e.name),g=h?.integration.checkExecution;if(!h||!m||g?.operationId!==a||g.key!==o||g.status!=="running"||g.child!==e.name||g.candidateCommit!==i||g.integrationCommit!==n||m.verifiedCommit!==i||Ks(h)!==n)throw new Error("Native Supervisor integration changed during checks");if(g.receiptRef=f,g.checks=p,v.length>0){let S=`Native Supervisor integration checks did not pass (${v.map(({name:N,reason:y})=>`${N}: ${y}`).join("; ")}); receipt ${f}`;throw g.status="interrupted",g.error=S,m.blocker=S,h.stateVersion+=1,await ge(e.paths,h),new Error(S)}g.status="completed";let w=DC(h,{name:e.name,integrationCommit:n,checks:p});return await ge(e.paths,w),w})}catch(u){throw await $(e.paths,"interrupt Supervisor integration checks",async()=>{let d=await ee(e.paths,r.parent),f=d?.integration.checkExecution;d&&f?.operationId===a&&f.key===o&&f.status==="running"&&(f.status="interrupted",f.error=u.message,d.stateVersion+=1,await ge(e.paths,d))}),u}}async function OV(e){let t=wi(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(Ks(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{A(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=A(r.integration.worktree,["rev-parse","HEAD"]),a=dr(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},fi(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await ge(e.paths,a),a}function HV(e,t){if(ji(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=dr(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function fu(e){let t=Ks(e);if(t===e.integration.headCommit)return e;try{A(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=dr(e);return r.integration.headCommit=t,fi(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function hu(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Ks(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return HV(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function pu(e){let r=await ee(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:h})=>h==="integrated"||h==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=kt(e.paths.projectRoot).map(h=>Ae.resolve(h)).find(h=>ne(h).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=Ae.resolve(n)===Ae.resolve(e.paths.projectRoot)?[Ae.relative(n,Ae.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Er(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=A(n,["rev-parse","HEAD"]);if((()=>{try{return A(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let h=await qC({paths:e.paths,state:r,targetCommit:o});if(await FC({paths:e.paths,plan:h,targetRoot:n}),r.children.every(({status:g})=>g==="archived"))return await $w(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let m=dr(r);for(let g of m.children)g.status="archived";return m.stateVersion+=1,await ge(e.paths,m),await $w(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:o}}let l=Ks(r);if(l!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let u=wi(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!u)return!1;try{return A(r.integration.worktree,["merge-base","--is-ancestor",u,l]),!0}catch{return!1}})();if(u!==l&&!d&&u!==r.integration.targetCommit&&await OV({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let f=await qC({paths:e.paths,state:r,targetCommit:l});u!==l&&A(n,["merge","--ff-only",r.integration.branch]);let p=A(n,["rev-parse","HEAD"]);if(p!==l)throw new Error("Native Supervisor target did not receive the verified integration head");let v=dr(r);for(let h of v.children)h.status="archived";return await FC({paths:e.paths,plan:f,targetRoot:n}),v.stateVersion+=1,await ge(e.paths,v),await $w(e.paths,r.parent),{state:v,targetRoot:n,targetCommit:p}}function QC(e,t){return Ae.join(WC(e,t),"cleanup.json")}function BC(e){let t=kt(e.paths.projectRoot).map(s=>Ae.resolve(s)),r=Ae.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:c,task:l})=>({root:c??l?.projectRoot??xV(ne(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Ae.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(CV(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Er(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=ne(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{A(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(An(e.paths.projectRoot,s))try{A(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function qC(e){let t=QC(e.paths,e.state.parent);try{let i=JSON.parse(await Oh.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=BC(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=BC(e);return await fe(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function FC(e){for(let t of e.plan.worktrees){if(!kt(e.paths.projectRoot).map(a=>Ae.resolve(a)).includes(Ae.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=ne(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await Wl(t),A(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)An(e.paths.projectRoot,t)&&A(e.targetRoot,["branch","-d",t])}async function $w(e,t){await Oh.rm(QC(e,t),{force:!0})}function qw(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Ow,PV,fn=_(()=>{"use strict";ho();$e();ct();gh();Kl();it();Q();tt();zt();qP();tn();lw();Eh();Ow="comet.native.supervisor.v2",PV=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var ZC={};ed(ZC,{NATIVE_CHILDREN_FILE:()=>Fw,NATIVE_CHILDREN_SCHEMA:()=>Po,NATIVE_CHILDREN_SCHEMA_V2:()=>Ww,NATIVE_CHILDREN_V2_SCHEMA:()=>Co,findNativeV1SupervisorParents:()=>zw,hasNativeSupervisorShapeIntent:()=>cx,hashNativeParentContract:()=>Xs,inspectNativeChildren:()=>vt,nativeChildrenAcceptanceValidation:()=>xo,nativeChildrenIndexDrift:()=>ox,parseNativeChildrenContract:()=>sx,readNativeChildrenContract:()=>$i,readNativeSupervisorShapeIntent:()=>mu});import{promises as Lw}from"node:fs";import fr from"node:path";function qh(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Bh(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function tx(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Mw(e,t){let r=fr.normalize(fr.resolve(e)),i=fr.normalize(fr.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function LV(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function rx(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function ox(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ww&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!ix(e.children,l)),nx(i)?i:null}if(e.schema===Po&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!ix(e.children,a)),nx(i)?i:null}return null}function ix(e,t){return e.some(r=>r.covers.includes(t))}function nx(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function xo(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function VV(e){let t=qh(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=qh(n,`Native children acceptance_index.${i}`);if(Bh(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function WV(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function sx(e,t,r={}){let i=(0,Vw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=qh(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Po&&a!==Co)throw Bh(n,ex,"Native children contract"),new Error(`Native children schema must be ${Po} or ${Co}`);let o=a===Po?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Bh(n,o==="indexed-v2"?BV:ex,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=qh(f,`Native child ${p}`);if(Bh(v,o==="indexed-v2"?MV:o==="summary-v2"?FV:qV,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!DV.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:tx(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?tx(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}LV(c);let d=r.policy==="advisory";if(a===Ww){if(o==="indexed-v2"){let f=VV(n.acceptance_index);d||WV(f,t,r);let p=Object.keys(f);return d||rx(c,p,p),{schema:Co,acceptance_index:f,children:c}}return{schema:Co,children:c}}return t&&!d&&rx(c,t),{schema:Po,children:c}}async function $i(e){let t=fr.join(e.changeDir,Fw);try{await Lw.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:Fw}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=sx(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?ox(a,e.acceptanceIds,e.validation??{}):null}}function zV(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function cx(e){let t=zV(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function mu(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return cx(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xs(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function lx(e){let t=kt(e.projectRoot);t.some(i=>Mw(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>fr.resolve(n)))]){let n=await X(i);n&&r.push({projectRoot:i,paths:await pe(i,n.native.artifact_root),parent:Mw(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function zw(e){let t=await lx(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Lw.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=fr.join(a.paths.changesDir,s.name),l;try{l=await Rt(fr.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await $i({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==Po||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:p})=>p.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:p,state:v})=>ne(p.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let p=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(p)i.push(`Native Supervisor parent ${a} targets ${p.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await vt({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let p=f.children.filter(({status:v})=>v!=="done").map(({name:v,status:h,message:m})=>`${v}=${h}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${p||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function JV(e,t){let r=fr.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Rt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GV(e,t){let r;try{r=await Lw.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=fr.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Rt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function UV(e,t,r){let i=fr.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${fr.sep}`))return null;let n=i.split(fr.sep).join("/");try{let a=(0,Vw.parseDocument)(A(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:z(a.toJS({mapAsMap:!1}))}catch{return null}}function KV(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function ax(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function vt(e){let t=fr.join(e.paths.changesDir,e.state.name),r=await mu(t),i=null,n;try{n=await $i({changeDir:t,validation:xo(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await ee(e.paths,e.state.name,{diagnostics:!0});if(g){let w=qw(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(S=>({...S,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Xs({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Co){let g=await ee(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let y=await Hh({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});y&&(g=y,await ge(e.paths,y))}}if(g){let N=qw(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(y=>({...y,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let w=new Map(n.contract.children.map(N=>[N.name,N])),S=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(y=>n.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==y))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of S){if(N.status!=="ready")continue;w.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:S,readyChildren:S.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await lx(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let S of await GV(g,l)){let N={...S,source:g,committedState:UV(g,S.file,w)};u.set(S.state.name,[...u.get(S.state.name)??[],N])}for(let S of l){let N=await JV(g,S);N&&d.set(S,[...d.get(S)??[],{source:g,state:N}])}}let f=new Map;for(let g of n.contract.children){let w=(u.get(g.name)??[]).find(({source:y,committedState:E})=>y.parent&&E?.name===g.name&&ax(E,o));if(w){f.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let S=u.get(g.name)?.[0];if(S){f.set(g.name,{kind:"blocked",phase:S.state.phase,projectRoot:S.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&f.set(g.name,KV(N[0].state,N[0].source,o))}let p=new Map(n.contract.children.map(g=>[g.name,g])),v=new Map,h=g=>{let w=v.get(g);if(w)return w;let S=p.get(g),y=S.depends_on.map(h).every(({status:I})=>I==="done"),E=f.get(g),P=E?.kind==="active"&&y?S.depends_on.filter(I=>!(u.get(I)??[]).some(({source:C,committedState:Ne})=>Mw(C.projectRoot,E.projectRoot)&&Ne?.name===I&&ax(Ne,o))):[],b,k=E?.message??null;E?.kind==="done"?(b=y?"done":"blocked",y||(k=`Native child ${g} was merged before its dependencies`)):E?.kind==="active"?(b=y&&P.length===0?"active":"blocked",y?P.length>0&&(k=`Native child ${g} does not include merged dependencies: ${P.join(", ")}`):k=`Native child ${g} started before its dependencies merged`):E?.kind==="blocked"?b="blocked":(b=s&&y?"ready":"pending",s||(k="Parent Shape confirmation is required"));let R={name:g,summary:S.summary,dependsOn:[...S.depends_on],covers:[...S.covers],status:b,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:k};return v.set(g,R),R},m=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:m.every(({status:g})=>g==="done")}}var Vw,Fw,Po,Co,Ww,DV,ex,BV,qV,FV,MV,ga=_(()=>{"use strict";Vw=Ha(Mn(),1);zt();tn();Jt();ct();tt();Q();ai();fn();Fw="children.yaml",Po="comet.native.children.v1",Co="comet.native.children.v2",Ww=Co,DV=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ex=new Set(["schema","children"]),BV=new Set(["schema","acceptance_index","children"]),qV=new Set(["name","depends_on","covers"]),FV=new Set(["name","summary","depends_on"]),MV=new Set(["name","depends_on","covers"])});import{pathToFileURL as xU}from"url";import fI from"node:path";zt();$e();Jt();Ee();tt();it();import{randomUUID as R1}from"node:crypto";import{promises as At}from"node:fs";import wt from"node:path";zt();$e();import{createHash as u1,randomUUID as ey}from"node:crypto";import{promises as hr}from"node:fs";import Ge from"node:path";Va();Ee();Jt();qr();Q();import{promises as Lg}from"fs";import NP from"path";var bP=["outcome","scope","nonGoals","acceptanceExamples"],xM=[...bP,"constraints","decisions","openQuestions","verificationExpectations"],AM=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],kP={maxFileBytes:bc};function SP(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
212
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function _M(e,t){let r=NP.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Lg.realpath(e),n=await Lg.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Lg.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Ml(e){return{valid:e.length===0,findings:e}}function Vg(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Wg(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:kP.maxFileBytes})).text}catch(a){return Ml([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of SP(i))n.set(nf(a)??a,o);for(let a of xM)n.has(a)||r.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of bP)(n.get(a)??"").length===0&&r.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return Vg(i)&&r.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Ml(r)}async function zg(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:kP.maxFileBytes})).text}catch(a){return Ml([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of SP(i))n.set(MS(a)??a,o);for(let a of AM)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Ml(r)}function ca(e,t){return NP.join(e.specsDir,t,"spec.md")}async function EP(e,t){let r=[],i=se(e,t.name);for(let n of t.spec_changes){let a=ca(e,n.capability),o=null;try{await j(e.nativeRoot,a),o=await Br(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await _M(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Ml(r)}Jt();ct();ga();fn();Ee();gh();ai();gl();vo();Kl();import{randomUUID as YV}from"node:crypto";var vu=3,Jw=2;function tr(e){return e.state_version+1}function XV(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function Gw(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Uw(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function QV(e){return(e??[]).map(t=>({name:ke(t.name),result:t.result,note:t.note?ke(t.note):null}))}function hn(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:ke(e.summary),completed_at:e.completedAt}}function ux(e){let t=z(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return z({...t,phase:"build",status:"active",state_version:tr(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function dx(e){let t=z(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return z({...t,status:"await-user",state_version:tr(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function fx(e){let t=z(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!HP(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=XV(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):Gw(t.acceptance),o=(r.now??new Date).toISOString();return z({...t,phase:"verify",state_version:tr(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??YV(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:ke(r.summary),addressed_acceptance_ids:i,checks:QV(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>ke(s)),known_limits_truncated:!1,review:{status:"passed",summary:ke(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function hx(e){let t=z(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return z({...t,state_version:tr(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function ZV(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function e1(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===ut?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:ke(e.response.result.summary),risks:e.response.result.risks.map(t=>ke(t)),risks_truncated:!1,completed_at:e.completedAt}}function px(e){let t=z(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Uw(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=DP({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(m=>[m.id,m])),o=t.acceptance.map(m=>{let g=a.get(m.id);return g?{...m,result:g.result,reason:ke(g.reason)}:m}),s=o.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),c=e1({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let w=Pt({...t,acceptance:o,verification:c},hn({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:z({...w,state_version:tr(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:Gw(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let m=Pt({...t,acceptance:o,verification:c},hn({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===ut;return{response:i,state:z({...m,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:tr(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:ke("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=Pt({...t,acceptance:o,verification:c},hn({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:z({...m,status:"await-user",state_version:tr(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:ke(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=ZV(t,s),d=l>=e.maxVerifyFailures,f=u>=3,p=d||f,v=f?"stalled":d?"budget":void 0,h=Pt({...t,acceptance:o,verification:c},hn({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:z({...h,phase:p?"verify":"build",status:p?"await-user":"active",state_version:tr(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:ke(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:ke("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function mx(e){let t=z(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==ut||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return z({...t,phase:"archive",status:"active",state_version:tr(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function vx(e){let t=z(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==ut||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Uw(t),n=Pt(t,hn({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return z({...n,status:"await-user",state_version:tr(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:ke(e.summary),risks:[ke("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:ke("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function gx(e){let t=z(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=ke(e.summary),n=Pt(t,hn({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return z({...n,phase:"archive",status:"active",state_version:tr(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:ke(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function wx(e,t){let r=z(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=Pt(r,hn({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return z({...i,status:"active",state_version:tr(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function yx(e){let t=z(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=vu,a=Pt(t,hn({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return z({...a,status:n?"blocked":"active",state_version:tr(t),blockers:n?[{owner:"runtime",reason:ke(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Nx(e){let t=z(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Uw(t),a=t.acceptance.some(({result:o})=>o==="passed");return z({...t,status:"active",state_version:tr(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Qs(e){let t=z(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Pt(t,hn({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?Gw(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return z({...i,phase:"build",status:"active",state_version:tr(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}$e();us();import{promises as kx}from"node:fs";import gu from"node:path";function Fh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mh(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Oi(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function bx(e,t){return e===null?null:Oi(e,t)}function Vh(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function t1(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function r1(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Lh(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Kw(e,t){if(e===null)return null;let r=Oi(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Yw(e,t){let r=Oi(e,t);if(!gu.isAbsolute(r))throw new Error(`${t} must be absolute`);return gu.resolve(r)}function i1(e,t){let r=`Native local checks[${t}]`,i=Fh(e,r);if(Mh(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Oi(l,`${r}.argv[${u}]`,!0)),a=Lh(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Kw(i.startedAt,`${r}.startedAt`),s=Kw(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Vh(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Oi(i.id,`${r}.id`),name:Oi(i.name,`${r}.name`),operationId:Oi(i.operationId,`${r}.operationId`),status:a,repeatable:r1(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Vh(i.executionCount,`${r}.executionCount`),argv:n,cwd:Yw(i.cwd,`${r}.cwd`),exitCode:t1(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Oi(i.log,`${r}.log`)}}function Xw(e){let t="Native local execution state",r=Fh(e,t);if(Mh(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ml)throw new Error(`Native local execution schema must be ${ml}`);let i=Fh(r.workspace,"Native local workspace");Mh(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Fh(r.execution,"Native local execution");Mh(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Kw(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Oi(o.operationId,"Native local execution.operationId"),stage:Lh(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Lh(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bx(o.executionId,"Native local execution.executionId"),status:Lh(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Vh(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(i1);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:ml,change:Oi(r.change,"Native local change"),basedOnStateVersion:Vh(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Yw(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Yw(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bx(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function Je(e){return Xw({schema:ml,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:gu.resolve(e.projectRoot),worktreeRoot:gu.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function hi(e){let t;try{t=await kx.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Xw(r)}async function we(e,t,r={}){let i=Xw(t);await kx.mkdir(gu.dirname(e),{recursive:!0}),await fe(e,i,r)}async function Qw(e){let t=null,r=null;try{t=await hi(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=Je(e);return await we(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}it();Af();ai();no();gl();vo();Kl();$e();Va();vo();import{promises as n1}from"node:fs";function wa(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
213
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function
|
|
214
|
-
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(wa).join(" ");return`| ${
|
|
209
|
+
`),e.omissionOverflow&&da(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(i+=1),n+=1,da(a,"omission",f)},s=f=>{i+=1,n+=1,da(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let p=r[f];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(f,1),p}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;eu(u)>No;){if(r.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(r.length/4));for(let v=0;v<p;v+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-p))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function hw(e){let t=Zi(e),r=t.entries.map((n,a)=>yL(n,`Snapshot entry ${a}`));if(r.sort(bL),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>NL(n,`Snapshot omission ${a}`));return i.sort(kL),SL({schema:ZP,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function tu(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:fa(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>Ft(r.path,i.path)||Ft(r.kind,i.kind))}function ru(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function JP(e){return e?{hash:e.hash,size:e.size}:null}function vw(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ft(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:JP(c),after:JP(l)})}}function rC(e,t){return{...e,attributedTo:t.filter(r=>ru(r,e.path))}}function bo(e){let t=tu(e.declaredArtifacts),r=[];return vw(e.baseline,e.current,i=>{r.push(rC(i,t))}),r}function on(e,t){return{id:`scope:${B(hL,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function EL(e,t){let r=t.omitted.map(i=>on({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(on({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(on({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function GP(e,t){return EL(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function pw(e,t){return Ft(e.kind,t.kind)||Ft(e.source,t.source)||wL(e.path,t.path)||Ft(e.id,t.id)}function RL(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(pw)}function iC(e){return[...new Set(e.map((t,r)=>fa(t,`Git path ${r}`)))].sort(Ft)}function UP(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function PL(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function nC(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=iC(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:UP(e.baseCommit,"Native external drift base commit"),targetBranch:PL(e.targetBranch,"Native external drift target branch"),targetCommit:UP(e.targetCommit,"Native external drift target commit"),paths:t}}function aC(e){if(typeof e.contractHash!="string"||!mw.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:tu(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:iC(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:nC(e.externalDrift)}}}function CL(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,f=0;return vw(e,t,p=>{let v=r.some(h=>ru(h,p.path));if(d+=1,c.push(p.path),!v&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<vL){let h=rC(p,r),m=eu(h);l+m<=No?(a.push(h),l+=m):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function oC(e,t){return on({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function xL(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:Bs(Number(t[1]),"Scope overflow change count"),unresolved:Bs(Number(t[2]),"Scope overflow unresolved count"),unattributed:Bs(Number(t[3]),"Scope overflow unattributed count")},i=yo(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(oC(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function AL(e){let t=QP("sha256");t.update(`${pL}
|
|
210
|
+
`);let r=0;vw(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){da(t,"change",n);let a=0;for(let o of e.declaredArtifacts)ru(o,n.path)&&(a+=1,da(t,"change-attribution",o));da(t,"change-end",{attributionCount:a}),a===0&&da(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&da(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function sC(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=CL(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let P=new Set(r.externalDrift.paths),b=new Set(o.changePaths),k=r.externalDrift.paths.filter(R=>!b.has(R)||n.some(I=>ru(I,R)));if(k.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${k.slice(0,8).join(", ")}`);if(P.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=B(Ql,e),c=B(Ql,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[P,b]of[["baseline",e],["current",t]])for(let k of b.omitted){if(l.length>=gL)break;l.push(on({kind:"snapshot-omission",source:P,path:k.path,evidence:{reason:k.reason,size:k.size,type:k.type}},`${P} snapshot omitted ${k.path}: ${k.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...GP("baseline",e),...GP("current",t),...o.totalChanges===0&&a===null?[on({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")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let P=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(b=>P.has(b)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(b=>!P.has(b))}},v=P=>{let b=o.candidates.slice(0,P.detailedChangeCount),k=b.filter(Ke=>Ke.attributedTo.length===0&&!u.has(Ke.path)),R=o.totalChanges-b.length,I=o.totalUnattributed-k.length,C=d-P.detailedOmissionCount,Ne=I+C,oe=[...k.map(Ke=>on({kind:"unattributed-change",source:"implementation-scope",path:Ke.path,evidence:{after:Ke.after,before:Ke.before,changeKind:Ke.kind}},`Changed path is not covered by a declared artifact: ${Ke.path}`)),...l.slice(0,P.detailedOmissionCount),...f,...Ne>0?[oC(P.overflowHash,{changes:R,unattributed:I,unresolved:Ne})]:[]],ce=RL(oe),Ue=P.includeGitAdvisory?p():void 0;return{schema:dw,contractHash:i,baselineProjectionRef:fw(s),baselineProjectionHash:s,currentProjectionRef:fw(c),currentProjectionHash:c,complete:ce.length===0,declaredArtifacts:n,changes:b,unattributed:k,unresolvedScopes:ce,noCodeReason:a,...Ue?{gitAdvisory:Ue}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,m=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let P=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:w});if(eu({...P,scopeHash:w})<=No)break;if(g){g=!1;continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let N=o.totalChanges>h||d>m?AL({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:m}):w,y=v({detailedChangeCount:h,detailedOmissionCount:m,includeGitAdvisory:g,overflowHash:N}),E={...y,scopeHash:B(eC,y)};if(eu(E)>No)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return E}function Fs(e){let t=hw(e.baseline),r=hw(e.current),i=aC(e);return{authority:i,baseline:t,current:r,scope:sC(t,r,i)}}function Ii(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ti(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function yo(e,t){if(typeof e!="string"||!mw.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function KP(e,t,r){let i=fw(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function qs(e,t){let r=Ii(e,"Native snapshot projection");if(Ti(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==ZP)throw new Error("Native snapshot projection schema is invalid");let i=Zi({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=hw(i);if(B(Ql,r)!==B(Ql,n))throw new Error("Native snapshot projection is not canonical");let a=B(Ql,n);if(t!==void 0&&yo(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function gw(e,t){let r=Ii(e,`Declared artifact ${t}`);if(Ti(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:fa(r.path,`Declared artifact ${t} path`),kind:r.kind}}function YP(e,t){if(e===null)return null;let r=Ii(e,t);return Ti(r,["hash","size"],[],t),{hash:yo(r.hash,`${t} hash`),size:Bs(r.size,`${t} size`)}}function XP(e,t){let r=Ii(e,`Implementation change ${t}`);if(Ti(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(gw),n=tu(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=YP(r.before,`Implementation change ${t} before`),o=YP(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:fa(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function IL(e,t){let r=Ii(e,`Unresolved scope ${t}`);Ti(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?tC(r.path,`Unresolved scope ${t} path`):fa(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Zl(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>fa(n,`${t} ${a}`)),i=[...new Set(r)].sort(Ft);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function cC(e){let t=Ii(e,"Native implementation external drift");if(Ti(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Zl(t.paths,"Native external drift paths");return nC({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Ms(e){let t=Ii(e,"Native implementation scope"),r=[..._L].filter(k=>k!=="gitAdvisory"&&k!=="externalDrift");if(Ti(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==dw)throw new Error("Native implementation scope schema is invalid");let i=yo(t.contractHash,"Implementation scope contractHash"),n=yo(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=KP(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=yo(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=KP(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(gw);if(JSON.stringify(c)!==JSON.stringify(tu(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(XP),u=[...l].sort((k,R)=>Ft(k.path,R.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(k=>k.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(k=>`${k.kind}:${k.path}`));if(l.some(k=>k.attributedTo.some(R=>!d.has(`${R.kind}:${R.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(k=>JSON.stringify(k.attributedTo)!==JSON.stringify(c.filter(R=>ru(R,k.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(XP),p=t.externalDrift===void 0?void 0:cC(t.externalDrift),v=new Set(p?.paths??[]),h=l.filter(k=>k.attributedTo.length===0&&!v.has(k.path));if(JSON.stringify(f)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let m=t.unresolvedScopes.map(IL),g=m.filter(k=>k.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:xL(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let S=t.noCodeReason,N=[...h.map(k=>on({kind:"unattributed-change",source:"implementation-scope",path:k.path,evidence:{after:k.after,before:k.before,changeKind:k.kind}},`Changed path is not covered by a declared artifact: ${k.path}`)),...l.length+(w?.changes??0)===0&&S===null?[on({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],y=m.filter(k=>k.kind==="unattributed-change"||k.kind==="missing-no-code-reason");if(JSON.stringify(m)!==JSON.stringify([...m].sort(pw))||new Set(m.map(k=>k.id)).size!==m.length||JSON.stringify(y)!==JSON.stringify(N.sort(pw))||t.complete!==(m.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let E;if(t.gitAdvisory!==void 0){let k=Ii(t.gitAdvisory,"Implementation scope Git advisory");if(Ti(k,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),k.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let R=Zl(k.changedPaths,"Git changed paths"),I=Zl(k.pathsPresentInSnapshotChanges,"Git present paths"),C=Zl(k.pathsAbsentFromSnapshotChanges,"Git absent paths"),Ne=[...I,...C].sort(Ft);if(JSON.stringify(Ne)!==JSON.stringify(R)||C.some(oe=>l.some(ce=>ce.path===oe)))throw new Error("Implementation scope Git advisory partition is invalid");E={advisoryOnly:!0,changedPaths:R,pathsPresentInSnapshotChanges:I,pathsAbsentFromSnapshotChanges:C}}let P={schema:dw,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:m,noCodeReason:S,...E?{gitAdvisory:E}:{},...p?{externalDrift:p}:{}},b=yo(t.scopeHash,"Implementation scope scopeHash");if(B(eC,P)!==b)throw new Error("Implementation scope content hash mismatch");return{...P,scopeHash:b}}function TL(e){let t=Ii(e,"Native implementation scope authority");if(Ti(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(gw);if(JSON.stringify(r)!==JSON.stringify(tu(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=Zl(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:cC(t.externalDrift),a=aC({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Ls(e){let t=Ii(e,"Native implementation scope bundle");Ti(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=TL(t.authority),i=qs(t.baseline),n=qs(t.current),a=Ms(t.scope),o=sC(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function lC(e){let t=Ms(e.scope);return Ls({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var dw,ZP,Ql,eC,hL,pL,mL,mw,No,vL,gL,_L,sn=_(()=>{"use strict";ct();na();dw="comet.native.implementation-scope.v2",ZP="comet.native.content-snapshot-projection.v1",Ql="comet.native.content-snapshot-projection.v1",eC="comet.native.implementation-scope.v2",hL="comet.native.unresolved-scope-id.v1",pL="comet.native.scope-detail-overflow.v1",mL="comet.native.snapshot-projection-overflow.v2",mw=/^[a-f0-9]{64}$/u,No=1024*1024,vL=128,gL=128;_L=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import uC from"node:path";function cn(e,t){if(!fC.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function hC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function pC(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function ww(e,t,r=2e3){let i=mt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function iu(e,t){let r=uC.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||uC.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function HL(e,t,r){let i=iu(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ni(i),a=i.toLowerCase(),o=r?iu(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function yw(e){let t=iu(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Vs(e,t){return e<t?-1:e>t?1:0}function Rh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ph(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function mC(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function dC(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function DL(e){let t=Rh(e,"Native acceptance trace");if(Ph(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!fC.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=iu(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Rh(o,`Native acceptance trace entry ${s}`);if(Ph(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>yw(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Vs))||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:iu(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:ww(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Vs(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=cn(t.traceHash,"Native acceptance trace hash");if(B(jL,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Ch(e){let t=Rh(e,"Native partial allowance");if(Ph(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Vs))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:pC(t.change),scopeHash:cn(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:ww(t.reason,"Partial allowance reason"),confirmedSummary:ww(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:hC(t.sourceRevision),confirmedAt:mC(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=cn(t.allowanceHash,"Native partial allowance hash");if(B($L,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function nu(e){let t=Rh(e,"Native verification evidence");if(Ph(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=cn(t.implementationScopeHash,"Native verification implementation scope hash"),i=DL(t.acceptanceTrace),n=cn(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:cn(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>yw(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Vs)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(Vs);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>yw(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Vs)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:pC(t.change),sourceRevision:hC(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:cn(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:dC(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:HL(t.reportRef,"Native verification report ref"),reportHash:cn(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:dC(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:mC(t.createdAt,"Native verification timestamp")},d=cn(t.envelopeHash,"Native verification envelope hash");if(B(OL,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var fC,jL,$L,OL,au=_(()=>{"use strict";ct();nn();Nc();sn();fC=/^[a-f0-9]{64}$/u,jL="comet.native.acceptance-trace.v2",$L="comet.native.partial-allowance.v1",OL="comet.native.verification-evidence.v2"});import vC from"node:path";function pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ma(e,t,r,i=[]){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function ln(e,t){if(typeof e!="string"||!BL.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function bC(e,t){let r=Pr(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function wC(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function zL(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>LL||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let r=vC.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||vC.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function JL(e){let t=pa(e,"Native check receipt checker");ma(t,["policy","version","hash","limits"],"Native check receipt checker");let r=pa(t.limits,"Native check receipt limits");if(ma(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ha||t.version!==ou||t.hash!==Ah||r.maxFiles!==je.maxFiles||r.maxFileBytes!==je.maxFileBytes||r.maxTotalBytes!==je.maxTotalBytes||r.maxIssues!==je.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ha,version:ou,hash:Ah,limits:{...je}}}function GL(e){let t=pa(e,"Native check receipt contract");return ma(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ln(t.expectedHash,"Native check expected contract hash"),beforeHash:ln(t.beforeHash,"Native check before contract hash"),afterHash:ln(t.afterHash,"Native check after contract hash")}}function UL(e){let t=pa(e,"Native check receipt implementation");return ma(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ln(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:ln(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ln(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ln(t.afterSnapshotHash,"Native check after snapshot hash")}}function KL(e,t){let r=pa(e,`Native check batch ${t}`);ma(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Pr(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Pr(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Pr(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Pr(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Pr(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Pr(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>je.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>je.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function YL(e){let t=pa(e,"Native check receipt counts");ma(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Pr(t.filesSelected,"Native check filesSelected"),filesScanned:Pr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Pr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Pr(t.bytesScanned,"Native check bytesScanned"),issueCount:Pr(t.issueCount,"Native check issueCount"),recordedIssueCount:Pr(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(KL):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>je.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>je.maxFiles||r.bytesScanned>je.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function XL(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||gC.indexOf(e.kind)-gC.indexOf(t.kind)}function QL(e){if(!Array.isArray(e)||e.length>je.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=pa(i,`Native check issue ${n}`);if(ma(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!VL.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:zL(a.path,`Native check issue ${n} path`),line:bC(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(XL);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function ZL(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!WL.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=NC.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function kC(e){return B(ML,e)}function un(e){let t=pa(e,"Native check receipt");if(ma(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==xh)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!qL.test(t.change))throw new Error("Native check receipt change name is invalid");let r=bC(t.sourceRevision,"Native check source revision"),i=JL(t.checker),n=GL(t.contract),a=UL(t.implementation),o=kC({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ln(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=wC(t.startedAt,"Native check receipt startedAt"),c=wC(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=YL(t.counts),u=QL(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=ZL(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>je.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>je.maxFiles&&!u.some(h=>h.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:xh,change:t.change,sourceRevision:r,checker:i,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=ln(t.receiptHash,"Native check receipt content hash");if(B(yC,p)!==v)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:v}}function SC(e){let t={policy:ha,version:ou,hash:Ah,limits:{...je}},r={schema:xh,...e,checker:t,inputHash:kC({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return un({...r,receiptHash:B(yC,r)})}var xh,yC,ha,ou,je,BL,qL,FL,ML,LL,Ah,VL,gC,NC,WL,Ws=_(()=>{"use strict";ct();xh="comet.native.check-receipt.v1",yC="comet.native.check-receipt.v1",ha="scoped-text-safety",ou=1,je=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),BL=/^[a-f0-9]{64}$/u,qL=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FL="comet.native.checker-policy.v1",ML="comet.native.check-input.v1",LL=2048,Ah=B(FL,{policy:ha,version:ou,limits:je,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),VL=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),gC=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],NC=["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"],WL=new Set(NC)});function zs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function va(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function dn(e,t){if(typeof e!="string"||!tV.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ui(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=mt(e).trim();if(!r||r.length>aV||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Nw(e,t){let r=ui(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function su(e,t,r=ui,i=!1,n=oV){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function cV(e,t){if(typeof e!="string"||!rV.test(e))throw new Error(`${t} is invalid`);return e}function lV(e){let t=zs(e,"Native verification receipt bindings");if(va(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!iV.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:dn(t.contractHash,"Native verification receipt contract hash"),scopeHash:dn(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:dn(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:dn(t.artifactHash,"Native verification receipt artifact hash")}}function uV(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=nV.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function dV(e,t,r,i){let n=zs(t,`Native ${e} evidence`);if(e==="automated-check"){if(va(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Nw(n.startedAt,"Native automated-check start time"),o=Nw(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=zs(n.worktree,"Native automated-check worktree");if(va(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=zs(n.afterFence,"Native automated-check after fence");if(va(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ui(n.executable,"Native automated-check executable"),args:su(n.args,"Native automated-check arguments",ui,!0),cwd:ui(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ui(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:dn(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:dn(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:dn(n.outputHash,"Native automated-check output hash"),outputSummary:ui(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){va(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=uV(n.checkReceiptRef);if(dn(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:su(n.subjects,"Native static inspection subjects",ui,i==="required-check"),rule:ui(n.rule,"Native static inspection rule"),resultSummary:ui(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return va(n,["steps","observations"],"Native manual-evidence evidence"),{steps:su(n.steps,"Native manual evidence steps"),observations:su(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function RC(e){let t=zs(e,"Native verification receipt");if(va(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=ui(t.actor,"Native verification receipt actor"),o=su(t.acceptanceIds,"Native receipt acceptance IDs",cV,i==="required-check",sV).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:_h,kind:r,role:i,status:n,bindings:lV(t.bindings),acceptanceIds:o,actor:a,issuedAt:Nw(t.issuedAt,"Native verification receipt issue time"),evidence:dV(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ha||s.actor!==`native-runtime:${ha}`))throw new Error("Native required check policy identity is invalid");return s}function PC(e){let t=RC({schema:_h,...e});return{...t,receiptHash:B(EC,t)}}function cu(e){let t=zs(e,"Native verification receipt");if(va(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==_h)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=RC(i),a=dn(t.receiptHash,"Native verification receipt hash");if(B(EC,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Ih(e){return B(eV,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var _h,EC,eV,tV,rV,iV,nV,aV,oV,sV,Js=_(()=>{"use strict";ct();Ws();nn();_h="comet.native.verification-receipt.v3",EC=_h,eV="comet.native.declared-artifacts.v1",tV=/^[a-f0-9]{64}$/u,rV=/^acceptance-[a-f0-9]{64}$/u,iV=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nV=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,aV=4096,oV=256,sV=1024});var $C={};ed($C,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>Wr,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>fV,listNativeVerificationReceiptRefs:()=>xw,nativeEvidenceRef:()=>fi,nativeReportEvidenceRef:()=>kw,readArchivedNativeVerificationAcceptanceCounts:()=>kV,readNativeImplementationScope:()=>Us,readNativeImplementationScopeBundle:()=>fn,readNativePartialAllowance:()=>du,readNativeVerificationEvidence:()=>Ro,readNativeVerificationReceipt:()=>Eo,readNativeVerificationReportSnapshot:()=>uu,removeNativeVerificationReportSnapshot:()=>Sw,writeNativeImplementationScope:()=>NV,writeNativePartialAllowance:()=>bV,writeNativeVerificationEvidence:()=>jC,writeNativeVerificationReceipt:()=>Cw,writeNativeVerificationReportSnapshot:()=>Gs});import{createHash as _C}from"node:crypto";import{promises as er}from"node:fs";import di from"node:path";function bw(e,t){let r=di.relative(e,t);return r===""||!di.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${di.sep}`)}function hV(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lu(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function CC(e){let t=await er.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await er.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function pV(e,t){let r=di.resolve(e),i=di.resolve(t);if(!bw(r,i))throw new Error("Native evidence path is outside its change");let n=[await CC(r)],a=r;for(let o of di.relative(r,i).split(di.sep).filter(Boolean)){a=di.join(a,o);let s=await CC(a);if(!bw(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function xC(e){for(let t of e){let r=await er.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hV(t,r)||await er.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function mV(e,t,r={}){let i=await pV(t,di.dirname(e));await r.afterParentChainCaptured?.();let n=await er.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await er.realpath(e);if(!bw(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await er.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),er.lstat(e),er.realpath(e)]);if(await xC(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!lu(s,n)||!lu(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Wr)throw new Error(`Native evidence document exceeds ${Wr} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let m=Wr+1-d,g=await o.read(f,0,Math.min(f.length,m),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>Wr)throw new Error(`Native evidence document exceeds ${Wr} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,v,h]=await Promise.all([o.stat(),er.lstat(e),er.realpath(e)]);if(await xC(i),!v.isFile()||v.isSymbolicLink()||h!==a||!lu(s,p)||!lu(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function fi(e,t){if(!IC.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function kw(e){return fi("reports",e)}async function Gs(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Wr||_C("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return So({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Sw(e){let t=Ew(e.paths,e.name,"reports",e.hash),r=F(e.paths,t);await j(r,t);let i=await er.lstat(t);if(await uu(e.paths,e.name,e.hash),await j(r,t),!lu(i,await er.lstat(t)))throw new Error("Native report evidence changed before rollback");await er.unlink(t)}async function uu(e,t,r,i,n){if(!IC.test(r))throw new Error("Native report evidence hash is invalid");let a=await ji({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});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!==r||typeof o.content!="string"||_C("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function ko(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function Ew(e,t,r,i,n){let a=fi(r,i);return n?di.join(n,...a.split("/")):Jn(V(e,t),a)}async function ji(e){let t=Ew(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??F(e.paths,t);return await j(r,t),mV(t,r,e.hooks)}async function So(e){Th(e.value);let t=Ew(e.paths,e.name,e.kind,e.hash),r=F(e.paths,t);await j(r,t);try{let n=await ji(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return fi(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await fe(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await ji(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return fi(e.kind,e.hash)}function Th(e){if(vV(e)>Wr)throw new Error(`Native evidence document exceeds ${Wr} bytes`)}function vV(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
211
|
+
`,"utf8")}function AC(e,t){return qs(e,t)}function gV(e,t){let r=Ms(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function TC(e,t,r){let i=Ch(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Rw(e,t,r){let i=nu(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function wV(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function yV(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,d=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(d)||l<0||u<0||d<0||u+d>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:d}}async function Pw(e,t,r,i=!1,n){let a=await Us(e,t,r.implementationScopeRef,void 0,n);if(i&&await uu(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await du(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function NV(e){let t=Ls(e.bundle),{baseline:r,current:i,scope:n}=t;return Th(r),Th(i),Th(n),await So({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await So({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),So({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function fn(e,t,r,i,n){let a=ko(r,"scopes"),o=gV(await ji({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=ko(o.baselineProjectionRef,"snapshots"),c=ko(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([ji({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>AC(d,s)),ji({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>AC(d,c))]);return lC({baseline:l,current:u,scope:o})}async function Us(e,t,r,i,n){return(await fn(e,t,r,i,n)).scope}async function bV(e){let t=TC(e.allowance,e.name,e.allowance.allowanceHash),r=await Us(e.paths,e.name,fi("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return So({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function du(e,t,r,i,n){let a=ko(r,"allowances");return TC(await ji({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function Cw(e){let t=cu(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return So({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Eo(e,t,r,i,n){let a=ko(r,"receipts"),o=cu(await ji({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function xw(e,t){let r=di.join(V(e,t),"evidence","receipts");await j(F(e,r),r);let i;try{i=await er.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>fi("receipts",n))}async function jC(e){let t=Rw(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Pw(e.paths,e.name,t,!0),So({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Ro(e,t,r,i,n){let a=ko(r,"verifications"),o=Rw(await ji({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Pw(e,t,o,!1,n),o}async function kV(e,t,r,i){let n=ko(r,"verifications"),a=await ji({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=yV(a,t,n);if(o)return o;let s=Rw(a,t,n);return await Pw(e,t,s,!1,i),wV(s.acceptanceTrace)}var IC,Wr,fV,zr=_(()=>{"use strict";Oe();Q();Ir();sn();au();Js();IC=/^[a-f0-9]{64}$/u,Wr=No,fV=3*Wr});var HC={};ed(HC,{executeNativeSupervisorChecks:()=>Tw,readNativeSupervisorCheckEvidence:()=>jh});import{createHash as SV,randomUUID as EV}from"node:crypto";import{promises as RV}from"node:fs";import OC from"node:path";function Iw(e){return SV("sha256").update(e).digest("hex")}function Aw(e,t){if(A(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||A(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!Er(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function _w(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function Tw(e){if(e.plans.length===0||new Set(e.plans.map(({id:s})=>s)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:s})=>!s))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:s,content:c})=>!s.trim()||Buffer.byteLength(c)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=B("comet.native.supervisor-check-plan.v1",{plans:e.plans,materials:e.materials}),r=await $(e.paths,"reserve Supervisor checks",async()=>{let s=await ee(e.paths,e.parent),c=_w(s,e.child,e.runId);Aw(e.parent,c),e.plans.forEach(u=>la(c.projectRoot,u));let l=c.checkExecution;if(l?.status==="running"){let u=await Ds(l.ownerPid,l.ownerIdentity),d=Date.parse(l.expiresAt??"")||Date.parse(l.startedAt)+3e4;if(u){if(!(Date.now()<d))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(l.key!==t)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(c),execute:!1}}let f=l.activeProcess;if(f===void 0||f?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${OC.join(He(e.paths,e.parent),"logs","checks")} for operation ${l.operationId}; stop any remaining check process in ${c.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${c.runId}, and dispatch a new Verifier for the preserved candidate.`);if(f&&await Ds(f.pid,f.identity)){if(!(Date.now()<d))throw new Error(`Native Supervisor check ${f.checkId} is still running as PID ${f.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(c),execute:!1}}l.status="interrupted"}return l?.status==="completed"&&l.key===t&&e.plans.every(({repeatable:u})=>u)?{task:structuredClone(c),execute:!1}:(c.checkExecution={operationId:EV(),key:t,status:"running",ownerPid:process.pid,ownerIdentity:await wo(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((u,d)=>u+d.timeoutMs,0)+3e4).toISOString()},c.checksReason="running",s.stateVersion+=1,await ge(e.paths,s),{task:structuredClone(c),execute:!0})}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.receiptRef&&await jh({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=He(e.paths,e.parent),o=async s=>{await $(e.paths,"register Supervisor check process",async()=>{let c=await ee(e.paths,e.parent),l=_w(c,e.child,e.runId);if(l.checkExecution?.operationId!==n||l.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");l.checkExecution.activeProcess=s,c.stateVersion+=1,await ge(e.paths,c)})};try{let s=[];for(let d of e.plans){await o({status:"starting",checkId:d.id});let f=await mo({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:d,onSpawn:async({pid:h})=>{await o({status:"running",checkId:d.id,pid:h,identity:await wo(h)??void 0})}});await o(null);let p=OC.join(a,f.logRef),v=await RV.readFile(p,"utf8");s.push({...f,logContent:mt(v).slice(0,128*1024)})}Aw(e.parent,i);let c={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:t,checks:s,materials:e.materials.map(({name:d,content:f})=>{let p=mt(f);return{name:d,content:p,hash:Iw(p)}})},l=JSON.stringify(c),u=await Gs({paths:e.paths,name:e.parent,hash:Iw(l),text:l});return await $(e.paths,"complete Supervisor checks",async()=>{let d=await ee(e.paths,e.parent),f=_w(d,e.child,e.runId);if(f.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Aw(e.parent,f),f.checkExecution.status="completed",f.checkExecution.receiptRef=u,f.checksReason="completed",d.stateVersion+=1,await ge(e.paths,d)}),{status:"completed",operationId:n,receiptRef:u}}catch(s){throw await $(e.paths,"interrupt Supervisor checks",async()=>{let c=await ee(e.paths,e.parent),l=c?.children.find(({name:u})=>u===e.child)?.task;l?.runId===e.runId&&l.checkExecution?.operationId===n&&(l.checkExecution.status="interrupted",l.checksReason="not-run",c.stateVersion+=1,await ge(e.paths,c))}),s}}async function jh(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await uu(e.paths,e.parent,t[1])),i=e.task;if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!Array.isArray(r.materials)||r.materials.some(({content:n,hash:a})=>Iw(n)!==a))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var jw=_(()=>{"use strict";ho();rn();lw();ct();gh();zr();it();Q();nn();hn()});import Ae from"node:path";import{randomUUID as MC}from"node:crypto";import{promises as Oh}from"node:fs";function CV(e,t){let r=Ae.relative(Ae.resolve(e),Ae.resolve(t));return r===""||!Ae.isAbsolute(r)&&!r.startsWith(`..${Ae.sep}`)}function LC(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function xV(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return BP(e,".worktrees",`${t}-${r}`)}async function VC(e){let t=Ae.join(".worktrees",`${e.parent}-integration`);return Xl({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:LC(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function AV(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Xl({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Ae.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function WC(e,t){return Ae.join(He(e,t),"supervisor")}function Ys(e,t){return Ae.join(WC(e,t),"state.json")}function zC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Ow)throw new Error(`Native Supervisor state schema must be ${Ow}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if($i(t.integration.targetCommit,"Native Supervisor target commit"),$i(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");$i(n.candidateCommit,"Native Supervisor integration candidate commit"),$i(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&$i(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if($i(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function ee(e,t,r={}){try{let i=await Oh.readFile(Ys(e,t),"utf8"),n=JSON.parse(i);if(zC(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(ga(),ZC)),{readNativePortableState:l}=await Promise.resolve().then(()=>(oi(),ng)),u=await l(Ae.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:Ae.join(o.changesDir,t),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:p})=>p===f.name)&&(f.acceptanceScope=$h(d.contract,f.name),f.contractHash=B("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(oi(),ng)),s=await o(Ae.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ge(e,t){zC(t),await Oh.mkdir(e.changesRuntimeDir,{recursive:!0}),await fe(Ys(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function $i(e,t){if(!PV.test(e))throw new Error(`${t} must be a Git commit`)}function dr(e){return structuredClone(e)}function hi(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function _V(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function IV(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Hw(e){$i(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:$h(e.contract,i.name),contractHash:B("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ow,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function $h(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Hh(e){let t=LC(e.parent),r=yi(e.paths.projectRoot,t);if(!r)return null;let i=yi(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=kt(e.paths.projectRoot).map(o=>Ae.resolve(o)).find(o=>ne(o).currentBranch===t);if(!n)return null;let a=Hw({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return hi(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function JC(e){let t=dr(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=$h(e.contract,n.name),s=B("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.status=n.candidateCommit?"needs-reverify":"ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."),n.acceptanceScope=o,n.contractHash=s}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:$h(e.contract,n.name),contractHash:B("comet.native.supervisor-contract.v1",e.contract)});return t.stateVersion+=1,t}function Dw(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=dr(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);_V(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,hi(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function TV(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function GC(e,t){let r=TV(e,t),i=dr(e);return hi(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function jV(e,t,r){let i=ne(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!Er(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=A(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return A(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return A(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(A(e,["merge","--ff-only",r]),A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function Ks(e){if(!Er(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=A(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Ae.resolve(t)!==Ae.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=A(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return A(e.integration.worktree,["rev-parse","HEAD"])}function $V(e,t,r){let i=ne(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!Er(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(A(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function Bw(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,hi(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Dh(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,hi(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function UC(e){return $(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await ee(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await X(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let d;try{d=await AV({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?$V(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):jV(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let v=dr(o),h=v.children.find(({name:m})=>m===l.name);h&&(h.blocker=p.message,hi(v,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let f=Dw(o,{role:u?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:MC()});o=f.state,s.push(f.task)}return(s.length>0||c)&&await ge(e.paths,o),{state:o,tasks:s}})}function KC(e,t){$i(t.candidateCommit,"Native Supervisor candidate commit");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,hi(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function YC(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=dr(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return ow({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),hi(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function DC(e,t){$i(t.integrationCommit,"Native Supervisor integration commit");let r=dr(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,hi(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function XC(e){let t=await $(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let d=await ee(e.paths,e.state.parent)??e.state,f=d.integration.checkExecution;if(f?.status==="running"){if(await Ds(f.ownerPid,f.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(f.activeProcess===void 0||f.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(f.activeProcess&&await Ds(f.activeProcess.pid,f.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(d.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let p=d.children.find(({name:w})=>w===e.name);if(!p)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=IV(d).find(({status:w})=>w!=="integrated"&&w!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(p.status!=="verified"||!p.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:N})=>!N))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:N})=>N)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(e.checkPlans.forEach(N=>la(d.integration.worktree,N)),!p.verification?.receiptRef||!p.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:w}=await Promise.resolve().then(()=>(jw(),HC)),S=await w({paths:e.paths,parent:d.parent,task:p.verification.execution,receiptRef:p.verification.receiptRef});if(S.candidateCommit!==p.verifiedCommit||S.checks.some(({status:N})=>N!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let h=Ks(d);if(h!==d.integration.headCommit){let w=(()=>{try{return A(d.integration.worktree,["merge-base","--is-ancestor",d.integration.headCommit,h]),!0}catch{return!1}})(),S=(()=>{try{return A(d.integration.worktree,["merge-base","--is-ancestor",p.verifiedCommit,h]),!0}catch{return!1}})();if(!w||!S)throw new Error(`Native Supervisor integration head drifted: expected ${d.integration.headCommit}, got ${h}`)}try{A(d.integration.worktree,["cat-file","-e",`${p.verifiedCommit}^{commit}`])}catch(w){throw new Error(`Native Supervisor verified commit is unavailable: ${p.verifiedCommit}`,{cause:w})}if(h===d.integration.headCommit){try{A(d.integration.worktree,["merge","--no-ff","--no-edit",p.verifiedCommit])}catch(w){throw new Error(`Native Supervisor integration conflict preserved in ${d.integration.worktree}`,{cause:w})}h=A(d.integration.worktree,["rev-parse","HEAD"])}let m=h;if(e.checkPlans){let w=MC(),S=B("comet.native.supervisor-integration-plan.v1",{child:e.name,candidateCommit:p.verifiedCommit,integrationCommit:m,plans:e.checkPlans});return d.integration.checkExecution={operationId:w,key:S,child:e.name,candidateCommit:p.verifiedCommit,integrationCommit:m,status:"running",ownerPid:process.pid,ownerIdentity:await wo(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null},d.stateVersion+=1,await ge(e.paths,d),{pending:{state:d,candidateCommit:p.verifiedCommit,integrationCommit:m,operationId:w,key:S}}}let g=DC(d,{name:e.name,integrationCommit:m,checks:e.checks});return await ge(e.paths,g),{completed:g}});if(t.completed)return t.completed;let{state:r,candidateCommit:i,integrationCommit:n,operationId:a,key:o}=t.pending,{writeNativeVerificationReportSnapshot:s}=await Promise.resolve().then(()=>(zr(),$C)),{createHash:c}=await import("node:crypto"),l=async u=>$(e.paths,"record Supervisor integration check process",async()=>{let d=await ee(e.paths,r.parent),f=d?.integration.checkExecution;if(!d||f?.operationId!==a||f.key!==o||f.status!=="running")throw new Error("Native Supervisor integration check operation is stale");f.activeProcess=u,d.stateVersion+=1,await ge(e.paths,d)});try{let u=[];for(let h of e.checkPlans)await l({status:"starting",checkId:h.id}),u.push(await mo({projectRoot:r.integration.worktree,runtimeDir:He(e.paths,r.parent),operationId:a,plan:h,onSpawn:async({pid:m})=>l({status:"running",checkId:h.id,pid:m,identity:await wo(m)??void 0})})),await l(null);let d=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:r.parent,child:e.name,candidateCommit:i,integrationCommit:n,operationId:a,planHash:o,results:u}),f=await s({paths:e.paths,name:r.parent,hash:c("sha256").update(d).digest("hex"),text:d}),p=u.map(h=>({name:h.name,status:h.status==="interrupted"?"incomplete":h.status,reason:h.status==="passed"?null:h.timedOut?"timed out":`exit ${h.exitCode??h.signal??"interrupted"}`,receiptRef:f})),v=p.filter(({status:h})=>h!=="passed");return await $(e.paths,"complete Supervisor integration checks",async()=>{let h=await ee(e.paths,r.parent),m=h?.children.find(({name:S})=>S===e.name),g=h?.integration.checkExecution;if(!h||!m||g?.operationId!==a||g.key!==o||g.status!=="running"||g.child!==e.name||g.candidateCommit!==i||g.integrationCommit!==n||m.verifiedCommit!==i||Ks(h)!==n)throw new Error("Native Supervisor integration changed during checks");if(g.receiptRef=f,g.checks=p,v.length>0){let S=`Native Supervisor integration checks did not pass (${v.map(({name:N,reason:y})=>`${N}: ${y}`).join("; ")}); receipt ${f}`;throw g.status="interrupted",g.error=S,m.blocker=S,h.stateVersion+=1,await ge(e.paths,h),new Error(S)}g.status="completed";let w=DC(h,{name:e.name,integrationCommit:n,checks:p});return await ge(e.paths,w),w})}catch(u){throw await $(e.paths,"interrupt Supervisor integration checks",async()=>{let d=await ee(e.paths,r.parent),f=d?.integration.checkExecution;d&&f?.operationId===a&&f.key===o&&f.status==="running"&&(f.status="interrupted",f.error=u.message,d.stateVersion+=1,await ge(e.paths,d))}),u}}async function OV(e){let t=yi(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(Ks(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{A(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=A(r.integration.worktree,["rev-parse","HEAD"]),a=dr(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},hi(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await ge(e.paths,a),a}function HV(e,t){if($i(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=dr(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function fu(e){let t=Ks(e);if(t===e.integration.headCommit)return e;try{A(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=dr(e);return r.integration.headCommit=t,hi(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function hu(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Ks(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return HV(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function pu(e){let r=await ee(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:h})=>h==="integrated"||h==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=kt(e.paths.projectRoot).map(h=>Ae.resolve(h)).find(h=>ne(h).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=Ae.resolve(n)===Ae.resolve(e.paths.projectRoot)?[Ae.relative(n,Ae.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Er(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=A(n,["rev-parse","HEAD"]);if((()=>{try{return A(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let h=await qC({paths:e.paths,state:r,targetCommit:o});if(await FC({paths:e.paths,plan:h,targetRoot:n}),r.children.every(({status:g})=>g==="archived"))return await $w(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let m=dr(r);for(let g of m.children)g.status="archived";return m.stateVersion+=1,await ge(e.paths,m),await $w(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:o}}let l=Ks(r);if(l!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let u=yi(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!u)return!1;try{return A(r.integration.worktree,["merge-base","--is-ancestor",u,l]),!0}catch{return!1}})();if(u!==l&&!d&&u!==r.integration.targetCommit&&await OV({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let f=await qC({paths:e.paths,state:r,targetCommit:l});u!==l&&A(n,["merge","--ff-only",r.integration.branch]);let p=A(n,["rev-parse","HEAD"]);if(p!==l)throw new Error("Native Supervisor target did not receive the verified integration head");let v=dr(r);for(let h of v.children)h.status="archived";return await FC({paths:e.paths,plan:f,targetRoot:n}),v.stateVersion+=1,await ge(e.paths,v),await $w(e.paths,r.parent),{state:v,targetRoot:n,targetCommit:p}}function QC(e,t){return Ae.join(WC(e,t),"cleanup.json")}function BC(e){let t=kt(e.paths.projectRoot).map(s=>Ae.resolve(s)),r=Ae.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:c,task:l})=>({root:c??l?.projectRoot??xV(ne(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Ae.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(CV(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Er(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=ne(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{A(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(An(e.paths.projectRoot,s))try{A(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function qC(e){let t=QC(e.paths,e.state.parent);try{let i=JSON.parse(await Oh.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=BC(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=BC(e);return await fe(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function FC(e){for(let t of e.plan.worktrees){if(!kt(e.paths.projectRoot).map(a=>Ae.resolve(a)).includes(Ae.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=ne(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await Wl(t),A(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)An(e.paths.projectRoot,t)&&A(e.targetRoot,["branch","-d",t])}async function $w(e,t){await Oh.rm(QC(e,t),{force:!0})}function qw(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Ow,PV,hn=_(()=>{"use strict";ho();Oe();ct();gh();Kl();it();Q();tt();zt();qP();rn();lw();Eh();Ow="comet.native.supervisor.v2",PV=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var ZC={};ed(ZC,{NATIVE_CHILDREN_FILE:()=>Fw,NATIVE_CHILDREN_SCHEMA:()=>Po,NATIVE_CHILDREN_SCHEMA_V2:()=>Ww,NATIVE_CHILDREN_V2_SCHEMA:()=>Co,findNativeV1SupervisorParents:()=>zw,hasNativeSupervisorShapeIntent:()=>cx,hashNativeParentContract:()=>Xs,inspectNativeChildren:()=>vt,nativeChildrenAcceptanceValidation:()=>xo,nativeChildrenIndexDrift:()=>ox,parseNativeChildrenContract:()=>sx,readNativeChildrenContract:()=>Oi,readNativeSupervisorShapeIntent:()=>mu});import{promises as Lw}from"node:fs";import fr from"node:path";function qh(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Bh(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function tx(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Mw(e,t){let r=fr.normalize(fr.resolve(e)),i=fr.normalize(fr.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function LV(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function rx(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function ox(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ww&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!ix(e.children,l)),nx(i)?i:null}if(e.schema===Po&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!ix(e.children,a)),nx(i)?i:null}return null}function ix(e,t){return e.some(r=>r.covers.includes(t))}function nx(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function xo(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function VV(e){let t=qh(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=qh(n,`Native children acceptance_index.${i}`);if(Bh(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function WV(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function sx(e,t,r={}){let i=(0,Vw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=qh(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Po&&a!==Co)throw Bh(n,ex,"Native children contract"),new Error(`Native children schema must be ${Po} or ${Co}`);let o=a===Po?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Bh(n,o==="indexed-v2"?BV:ex,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,p)=>{let v=qh(f,`Native child ${p}`);if(Bh(v,o==="indexed-v2"?MV:o==="summary-v2"?FV:qV,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!DV.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:tx(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?tx(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}LV(c);let d=r.policy==="advisory";if(a===Ww){if(o==="indexed-v2"){let f=VV(n.acceptance_index);d||WV(f,t,r);let p=Object.keys(f);return d||rx(c,p,p),{schema:Co,acceptance_index:f,children:c}}return{schema:Co,children:c}}return t&&!d&&rx(c,t),{schema:Po,children:c}}async function Oi(e){let t=fr.join(e.changeDir,Fw);try{await Lw.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await re({root:e.changeDir,ref:Fw}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=sx(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?ox(a,e.acceptanceIds,e.validation??{}):null}}function zV(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function cx(e){let t=zV(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function mu(e){try{let t=await re({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return cx(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xs(e){return B("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function lx(e){let t=kt(e.projectRoot);t.some(i=>Mw(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>fr.resolve(n)))]){let n=await X(i);n&&r.push({projectRoot:i,paths:await pe(i,n.native.artifact_root),parent:Mw(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function zw(e){let t=await lx(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Lw.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=fr.join(a.paths.changesDir,s.name),l;try{l=await Rt(fr.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await Oi({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==Po||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:p})=>p.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:p,state:v})=>ne(p.projectRoot).currentBranch===v.workspace.change_branch);if(!c){let p=o.find(({state:v})=>v.workspace.target_branch!==e.targetBranch);if(p)i.push(`Native Supervisor parent ${a} targets ${p.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let v=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${v.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await vt({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let p=f.children.filter(({status:v})=>v!=="done").map(({name:v,status:h,message:m})=>`${v}=${h}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${p||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function JV(e,t){let r=fr.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Rt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function GV(e,t){let r;try{r=await Lw.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=fr.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Rt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function UV(e,t,r){let i=fr.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${fr.sep}`))return null;let n=i.split(fr.sep).join("/");try{let a=(0,Vw.parseDocument)(A(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:z(a.toJS({mapAsMap:!1}))}catch{return null}}function KV(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function ax(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function vt(e){let t=fr.join(e.paths.changesDir,e.state.name),r=await mu(t),i=null,n;try{n=await Oi({changeDir:t,validation:xo(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await ee(e.paths,e.state.name,{diagnostics:!0});if(g){let w=qw(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(S=>({...S,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Xs({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Co){let g=await ee(e.paths,e.state.name,{diagnostics:!0});if(!g){let N=e.state.workspace.change_branch??e.state.workspace.target_branch;if(N){let y=await Hh({paths:e.paths,parent:e.state.name,targetBranch:N,contract:n.contract});y&&(g=y,await ge(e.paths,y))}}if(g){let N=qw(g);return e.state.children_contract_hash!==a||n.drift?{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(y=>({...y,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...N,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&N.confirmed}}let w=new Map(n.contract.children.map(N=>[N.name,N])),S=n.contract.children.map(N=>({name:N.name,summary:N.summary,dependsOn:[...N.depends_on],covers:[],status:s&&N.depends_on.every(y=>n.contract.children.filter(({name:E})=>E!==N.name).every(({name:E})=>E!==y))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let N of S){if(N.status!=="ready")continue;w.get(N.name).depends_on.length>0&&(N.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:S,readyChildren:S.filter(({status:N})=>N==="ready").map(({name:N})=>N),allDone:!1}}let c=await lx(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let S of await GV(g,l)){let N={...S,source:g,committedState:UV(g,S.file,w)};u.set(S.state.name,[...u.get(S.state.name)??[],N])}for(let S of l){let N=await JV(g,S);N&&d.set(S,[...d.get(S)??[],{source:g,state:N}])}}let f=new Map;for(let g of n.contract.children){let w=(u.get(g.name)??[]).find(({source:y,committedState:E})=>y.parent&&E?.name===g.name&&ax(E,o));if(w){f.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let S=u.get(g.name)?.[0];if(S){f.set(g.name,{kind:"blocked",phase:S.state.phase,projectRoot:S.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let N=d.get(g.name)??[];N.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):N[0]&&f.set(g.name,KV(N[0].state,N[0].source,o))}let p=new Map(n.contract.children.map(g=>[g.name,g])),v=new Map,h=g=>{let w=v.get(g);if(w)return w;let S=p.get(g),y=S.depends_on.map(h).every(({status:I})=>I==="done"),E=f.get(g),P=E?.kind==="active"&&y?S.depends_on.filter(I=>!(u.get(I)??[]).some(({source:C,committedState:Ne})=>Mw(C.projectRoot,E.projectRoot)&&Ne?.name===I&&ax(Ne,o))):[],b,k=E?.message??null;E?.kind==="done"?(b=y?"done":"blocked",y||(k=`Native child ${g} was merged before its dependencies`)):E?.kind==="active"?(b=y&&P.length===0?"active":"blocked",y?P.length>0&&(k=`Native child ${g} does not include merged dependencies: ${P.join(", ")}`):k=`Native child ${g} started before its dependencies merged`):E?.kind==="blocked"?b="blocked":(b=s&&y?"ready":"pending",s||(k="Parent Shape confirmation is required"));let R={name:g,summary:S.summary,dependsOn:[...S.depends_on],covers:[...S.covers],status:b,phase:E?.phase??null,projectRoot:E?.projectRoot??null,message:k};return v.set(g,R),R},m=n.contract.children.map(({name:g})=>h(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:m.every(({status:g})=>g==="done")}}var Vw,Fw,Po,Co,Ww,DV,ex,BV,qV,FV,MV,ga=_(()=>{"use strict";Vw=Ha(Mn(),1);zt();rn();Jt();ct();tt();Q();oi();hn();Fw="children.yaml",Po="comet.native.children.v1",Co="comet.native.children.v2",Ww=Co,DV=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ex=new Set(["schema","children"]),BV=new Set(["schema","acceptance_index","children"]),qV=new Set(["name","depends_on","covers"]),FV=new Set(["name","summary","depends_on"]),MV=new Set(["name","depends_on","covers"])});import{pathToFileURL as xU}from"url";import fI from"node:path";zt();Oe();Jt();Ee();tt();it();import{randomUUID as R1}from"node:crypto";import{promises as At}from"node:fs";import wt from"node:path";zt();Oe();import{createHash as u1,randomUUID as ey}from"node:crypto";import{promises as hr}from"node:fs";import Ge from"node:path";Va();Ee();Jt();qr();Q();import{promises as Lg}from"fs";import NP from"path";var bP=["outcome","scope","nonGoals","acceptanceExamples"],xM=[...bP,"constraints","decisions","openQuestions","verificationExpectations"],AM=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],kP={maxFileBytes:bc};function SP(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
212
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function _M(e,t){let r=NP.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await Lg.realpath(e),n=await Lg.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Lg.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Ml(e){return{valid:e.length===0,findings:e}}function Vg(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Wg(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:kP.maxFileBytes})).text}catch(a){return Ml([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of SP(i))n.set(nf(a)??a,o);for(let a of xM)n.has(a)||r.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of bP)(n.get(a)??"").length===0&&r.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return Vg(i)&&r.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Ml(r)}async function zg(e,t){let r=[],i;try{i=(await re({root:e,ref:t,maxBytes:kP.maxFileBytes})).text}catch(a){return Ml([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of SP(i))n.set(MS(a)??a,o);for(let a of AM)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return Ml(r)}function ca(e,t){return NP.join(e.specsDir,t,"spec.md")}async function EP(e,t){let r=[],i=se(e,t.name);for(let n of t.spec_changes){let a=ca(e,n.capability),o=null;try{await j(e.nativeRoot,a),o=await Br(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await _M(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Ml(r)}Jt();ct();ga();hn();Ee();gh();oi();gl();vo();Kl();import{randomUUID as YV}from"node:crypto";var vu=3,Jw=2;function tr(e){return e.state_version+1}function XV(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function Gw(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Uw(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function QV(e){return(e??[]).map(t=>({name:ke(t.name),result:t.result,note:t.note?ke(t.note):null}))}function pn(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:ke(e.summary),completed_at:e.completedAt}}function ux(e){let t=z(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return z({...t,phase:"build",status:"active",state_version:tr(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function dx(e){let t=z(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return z({...t,status:"await-user",state_version:tr(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function fx(e){let t=z(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!HP(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=XV(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):Gw(t.acceptance),o=(r.now??new Date).toISOString();return z({...t,phase:"verify",state_version:tr(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??YV(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:ke(r.summary),addressed_acceptance_ids:i,checks:QV(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>ke(s)),known_limits_truncated:!1,review:{status:"passed",summary:ke(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function hx(e){let t=z(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return z({...t,state_version:tr(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function ZV(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function e1(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===ut?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:ke(e.response.result.summary),risks:e.response.result.risks.map(t=>ke(t)),risks_truncated:!1,completed_at:e.completedAt}}function px(e){let t=z(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Uw(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=DP({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:m})=>m==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(m=>[m.id,m])),o=t.acceptance.map(m=>{let g=a.get(m.id);return g?{...m,result:g.result,reason:ke(g.reason)}:m}),s=o.filter(({result:m})=>m==="failed"||m==="blocked").map(({id:m})=>m),c=e1({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let w=Pt({...t,acceptance:o,verification:c},pn({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:z({...w,state_version:tr(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:Gw(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let m=Pt({...t,acceptance:o,verification:c},pn({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===ut;return{response:i,state:z({...m,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:tr(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:ke("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let m=Pt({...t,acceptance:o,verification:c},pn({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:z({...m,status:"await-user",state_version:tr(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:ke(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=ZV(t,s),d=l>=e.maxVerifyFailures,f=u>=3,p=d||f,v=f?"stalled":d?"budget":void 0,h=Pt({...t,acceptance:o,verification:c},pn({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:z({...h,phase:p?"verify":"build",status:p?"await-user":"active",state_version:tr(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:ke(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:ke("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function mx(e){let t=z(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==ut||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return z({...t,phase:"archive",status:"active",state_version:tr(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function vx(e){let t=z(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==ut||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Uw(t),n=Pt(t,pn({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return z({...n,status:"await-user",state_version:tr(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:ke(e.summary),risks:[ke("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:ke("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function gx(e){let t=z(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=ke(e.summary),n=Pt(t,pn({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return z({...n,phase:"archive",status:"active",state_version:tr(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:ke(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function wx(e,t){let r=z(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=Pt(r,pn({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return z({...i,status:"active",state_version:tr(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function yx(e){let t=z(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=vu,a=Pt(t,pn({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return z({...a,status:n?"blocked":"active",state_version:tr(t),blockers:n?[{owner:"runtime",reason:ke(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Nx(e){let t=z(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Uw(t),a=t.acceptance.some(({result:o})=>o==="passed");return z({...t,status:"active",state_version:tr(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Qs(e){let t=z(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Pt(t,pn({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?Gw(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return z({...i,phase:"build",status:"active",state_version:tr(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}Oe();us();import{promises as kx}from"node:fs";import gu from"node:path";function Fh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Mh(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Hi(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function bx(e,t){return e===null?null:Hi(e,t)}function Vh(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function t1(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function r1(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Lh(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Kw(e,t){if(e===null)return null;let r=Hi(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Yw(e,t){let r=Hi(e,t);if(!gu.isAbsolute(r))throw new Error(`${t} must be absolute`);return gu.resolve(r)}function i1(e,t){let r=`Native local checks[${t}]`,i=Fh(e,r);if(Mh(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Hi(l,`${r}.argv[${u}]`,!0)),a=Lh(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Kw(i.startedAt,`${r}.startedAt`),s=Kw(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Vh(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Hi(i.id,`${r}.id`),name:Hi(i.name,`${r}.name`),operationId:Hi(i.operationId,`${r}.operationId`),status:a,repeatable:r1(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Vh(i.executionCount,`${r}.executionCount`),argv:n,cwd:Yw(i.cwd,`${r}.cwd`),exitCode:t1(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Hi(i.log,`${r}.log`)}}function Xw(e){let t="Native local execution state",r=Fh(e,t);if(Mh(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ml)throw new Error(`Native local execution schema must be ${ml}`);let i=Fh(r.workspace,"Native local workspace");Mh(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Fh(r.execution,"Native local execution");Mh(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Kw(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Hi(o.operationId,"Native local execution.operationId"),stage:Lh(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Lh(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bx(o.executionId,"Native local execution.executionId"),status:Lh(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Vh(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(i1);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:ml,change:Hi(r.change,"Native local change"),basedOnStateVersion:Vh(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Yw(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Yw(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bx(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function Je(e){return Xw({schema:ml,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:gu.resolve(e.projectRoot),worktreeRoot:gu.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function pi(e){let t;try{t=await kx.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Xw(r)}async function we(e,t,r={}){let i=Xw(t);await kx.mkdir(gu.dirname(e),{recursive:!0}),await fe(e,i,r)}async function Qw(e){let t=null,r=null;try{t=await pi(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=Je(e);return await we(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}it();Af();oi();no();gl();vo();Kl();Oe();Va();vo();import{promises as n1}from"node:fs";function wa(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
213
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function mn(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function a1(e){return e.archived?or(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?or(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?or(e.language,"Verification passed; ready to archive","验收通过,可归档"):or(e.language,"Verification passed","验收通过")}function o1(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?or(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?a1(e):e.verification_result==="blocked"?or(t,"Blocked","已阻塞"):e.verification_result==="fail"?or(t,"Failed","未通过"):or(t,"Pending","待处理")}function s1(e){if(e.verification?.assurance==="semantic-verification-unavailable")return or(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return or(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return or(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===ut?ut:"host-attested"),r=t===ut&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function c1(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Av(r,d),n=(d,f)=>or(r,d,f),a=e.acceptance.map(d=>`| ${mn(d.id)} | ${mn(d.result)} | ${mn(d.source)} | ${mn(d.text)} | ${mn(wa(d.reason))} |`).join(`
|
|
214
|
+
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(wa).join(" ");return`| ${mn(wa(d.name))} | ${mn(f||"—")} | ${mn(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
215
215
|
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${wa(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
216
216
|
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${wa(d)}`).join(`
|
|
217
|
-
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${
|
|
217
|
+
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${mn(wa(d.summary))} | ${d.completed_at} |`)].join(`
|
|
218
218
|
`),u=t?.finalVerification.layers?`
|
|
219
219
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
220
220
|
|
|
@@ -268,17 +268,17 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
|
|
|
268
268
|
`:""}## ${i("conclusion")}
|
|
269
269
|
|
|
270
270
|
${wa(e.verification.summary)}
|
|
271
|
-
`}function l1(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function wu(e){let t;try{t=await n1.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=l1(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function mn(e){await xe(e.file,c1(e.state,e.supervisor))}Q();Va();zr();tt();var yu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,d1="comet-state.yaml",f1="state.json",$X=Qc("en");function ya(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ye(e,t){if(!yu.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Ge.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function pr(e,t){return Ge.join(ye(e,t),d1)}function ue(e,t){return Ge.join(Oe(e,t),f1)}async function Be(e,t){try{let r=await hr.readFile(pr(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function h1(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function xt(e){return ne(e).currentBranch}function p1(e,t){if(!t)return;let r=ne(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Ex(e){return $(e.paths,`create portable change ${e.name}`,async()=>{if(!yu.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await X(e.paths.projectRoot)===null&&await Nr(e.paths.projectRoot,e.initialProjectConfig),p1(e.paths.projectRoot,e.workspaceBinding);let t=(await yP(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Is(e.workspaceBinding?.isolation??"current",t);let r=ye(e.paths,e.name),i=Oe(e.paths,e.name);await Promise.all([j(e.paths.nativeRoot,r),j(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await hr.mkdir(e.paths.changesDir,{recursive:!0}),await hr.mkdir(r,{recursive:!1}),n=!0,await hr.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await hr.mkdir(i,{recursive:!1}),a=!0,await hr.mkdir(Ge.join(r,"specs"),{recursive:!0}),await xe(Ge.join(r,"brief.md"),Qc(e.language));let o=ig({name:e.name,language:e.language,workspace:h1(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await hs(pr(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await we(ue(e.paths,e.name),Je({portableState:o,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await hr.rm(i,{recursive:!0,force:!0}),n&&await hr.rm(r,{recursive:!0,force:!0}),o}})}async function L(e,t){return Rt(pr(e,t))}async function gt(e){let t=await Gn({file:pr(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=Ge.join(ye(e.paths,t.name),"verification.md");await j(e.paths.nativeRoot,r),await hr.rm(r,{force:!0})}return t}async function ty(e){let t=ye(e.paths,e.state.name),r=Ge.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await hr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!yu.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Ge.join(t,...s.split("/")),l=await hr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Ge.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await hr.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Gh(e){let t=ye(e.paths,e.state.name),r=await re({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Vg(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await re({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:D("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:xf({briefMarkdown:r.text,specs:i}),formalHash:D("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:D("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function Uh(e){return D("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Rx(e){return $(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await ty({paths:e.paths,state:t}),i=await Gh({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await $i({changeDir:ye(e.paths,t.name),acceptanceIds:n.map(({id:d})=>d),validation:xo({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await mu(ye(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:Uh({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=dx({state:c,acceptance:n.map(d=>({...d}))});a&&(l.children_contract_hash=Xs({acceptance:l.acceptance,children:a.contract}));let u=await gt({paths:e.paths,previous:t,next:l});return await we(ue(e.paths,t.name),Je({portableState:u,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),u})}async function Px(e){return $(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await Hi({paths:e.paths,state:t});let r=await ty({paths:e.paths,state:t}),i=await Gh({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await $i({changeDir:ye(e.paths,t.name),acceptanceIds:n.map(({id:h})=>h),validation:xo({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await mu(ye(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=Uh({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let h=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await ku({paths:e.paths,state:t,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}let l=ux({state:{...t,spec_changes:r},acceptance:n.map(h=>({...h}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Xs({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let h=[...t.history].reverse().find(({outcome:m})=>m==="pass"||m==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let m=await vt({paths:e.paths,state:l}),g=new Map((m?.children??[]).map(({name:N,status:y})=>[N,y])),w=new Set(a.contract.children.filter(({name:N})=>{let y=g.get(N);return y!=="done"&&y!=="integrated"&&y!=="archived"}).flatMap(({covers:N})=>N)),S=h.unresolved_ids.filter(N=>!w.has(N));if(S.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${S.join(", ")}`)}}let u=null,d=a?.contract.schema==="comet.native.children.v2"?await ee(e.paths,t.name):null,f=null,p=null;if(a?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.change_branch??t.workspace.target_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(p=wi(e.paths.projectRoot,f),!p)throw new Error(`Native Supervisor target branch has no commit: ${f}`);d||(d=await Hh({paths:e.paths,parent:t.name,targetBranch:f,contract:a.contract})),d||(u=await VC({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await X(e.paths.projectRoot)}))}let v=await gt({paths:e.paths,previous:t,next:l});if(await we(ue(e.paths,t.name),Je({portableState:v,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&f&&p){let h=d?JC({state:d,contract:a.contract}):u?Hw({parent:v.name,targetBranch:f,targetCommit:p,integrationBranch:u.binding.changeBranch,integrationWorktree:u.projectRoot,contract:a.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ge(e.paths,h)}return v})}async function Ao(e){let t=await ty(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Gh({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!Zv(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await $i({changeDir:ye(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:xo({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Uh({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Xs({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Hi(e){let t=await Ao(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await ku({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Cx(e){return $(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(await Hi({paths:e.paths,state:t}),await $i({changeDir:ye(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:xo(t)})||t.children_contract_hash){let a=await vt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=fx({state:t,input:e.input}),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Nu(e){let t=await L(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await vt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}async function xx(e){let t=await zw({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await Nu({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}function ry(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:vh(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function Ax(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...ry(t,r,i),executionCount:e.executionCount}}function _x(e,t){let r=Ge.relative(Ge.resolve(e),Ge.resolve(t));if(Ge.isAbsolute(r)||r===".."||r.startsWith(`..${Ge.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Ge.sep).join("/");return vh(e,i),i}function Zw(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Jl({id:e.id,name:e.id,executable:r,argv:i,cwdRef:_x(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function m1(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Zs(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:ke(i),argv_display:rw(r.argv.slice(1)).map(n=>ke(n)),argv_truncated:!1,cwd_ref:_x(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:m1(r)}})}function v1(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function bu(e){if(e.local===null||e.local.change!==e.state.name)return Je({portableState:e.state,projectRoot:e.projectRoot,branch:xt(e.projectRoot)});let t=e.local.execution?.operationId??ey();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function ec(e){try{let t=await hi(ue(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Ix(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function g1(e){let{state:t,local:r,envelope:i}=e;if(!wh(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function w1(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Jh(e){let t=await ec({paths:e.paths,state:e.state}),r=yx({state:e.state,summary:e.summary}),i=await gt({paths:e.paths,previous:e.state,next:r});return await we(ue(e.paths,e.state.name),bu({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Sx(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>Zw(i,r)===Jl(t[n]))}async function y1(e){return $(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(await Hi({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=ue(e.paths,t.name),i=(await Qw({file:r,portableState:t,projectRoot:e.projectRoot,branch:xt(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Sx(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:u})=>[l,u]));return{kind:"reuse",state:t,checks:Zs({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Qs({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(u=>!u.repeatable).map(({id:u})=>u).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await gt({paths:e.paths,previous:t,next:c});throw await we(ue(e.paths,t.name),Je({portableState:l,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(u=>!u.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Sx(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=ey(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?Ax(s,o,n,e.projectRoot):s?{...s,operationId:n}:ry(o,n,e.projectRoot)})};return await we(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function Wh(e){return $(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await L(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=ue(e.paths,t.name),i=await hi(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await we(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Tx(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){la(t,c);let l=Jl(c);i.has(l)||(i.add(l),r.push(c))}let n=await y1({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=Oe(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Wh({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>f.id===c.id?{...f,status:"running",executionCount:f.executionCount+1,startedAt:l}:f)})});let u=await mo({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await Wh({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>f.id===c.id?{...f,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef}:f)})})}await Wh({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Wh({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)})})}catch{}throw c}let s=await hi(ue(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Zs({local:s,projectRoot:t,supplied:[]})}}async function N1(e){let t=ue(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Jw)throw new Error(`Native Verifier request-checks exceeded ${Jw} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let v=Zw(p,e.projectRoot);n.set(v,p),p.status!=="interrupted"&&i.set(v,p),a.set(p.id,v)}let o=new Map,s=new Map;for(let p of e.response.checks){let v=v1(p);la(e.projectRoot,v);let h=Jl(v),m=s.get(v.id);if(m!==void 0&&m!==h)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let g=a.get(v.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,v)}let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,d=new Map(c.map(([,p])=>[p.id,p.name])),f={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(p=>{let v=Zw(p,e.projectRoot),h=o.get(v);return h&&p.status==="interrupted"?Ax(p,h,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>ry(p,r.execution.operationId,e.projectRoot))]};return await we(t,f,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:f,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function zh(e){return $(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await L(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=ue(e.paths,t.name),i=await hi(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await we(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function b1(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await zh({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await mo({projectRoot:e.projectRoot,runtimeDir:Oe(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await zh({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await zh({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await zh({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Zs({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function jx(e){return $(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Hi({paths:e.paths,state:t});let i=(await Qw({file:ue(e.paths,t.name),portableState:t,projectRoot:r,branch:xt(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Zs({local:i,projectRoot:r,supplied:e.checks});let n=hx(t),a=await gt({paths:e.paths,previous:t,next:n}),o=ue(e.paths,t.name),s=ey();return await we(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function $x(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await $(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await L(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Hi({paths:e.paths,state:r});let n=await ec({paths:e.paths,state:r}),a=g1({state:r,local:n,envelope:e.envelope}),o;try{o=aw(a.payload)}catch(d){let f=`Native Verifier response was invalid: ${d.message}`,p=await Jh({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${vu} was recorded`,{cause:d})}let s=w1(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Zs({local:n,projectRoot:i,supplied:e.checks}));let d=px({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let f=await N1({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:f}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){let f=`Native Verifier response was invalid: ${d.message}`,p=await Jh({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${vu} was recorded`,{cause:d})}let u=await gt({paths:e.paths,previous:r,next:l.state});return await we(ue(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?bu({local:n,state:u,projectRoot:i}):Je({portableState:u,projectRoot:i,branch:xt(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await mn({file:Ge.join(ye(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await b1({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await $(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await L(e.paths,e.name);return a.state_version!==t.state.state_version?null:Jh({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${vu} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Ox(e){return $(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await L(e.paths,e.name),r=await ec({paths:e.paths,state:t});if(Ix({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Jh({paths:e.paths,state:t,summary:e.summary})})}async function Hx(e){return $(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name);await Hi({paths:e.paths,state:t});let r=await ec({paths:e.paths,state:t}),i=Ix({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Zs({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=vx({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await gt({paths:e.paths,previous:t,next:a});return await we(ue(e.paths,t.name),bu({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await mn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:o}),o})}async function Dx(e){return $(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Hi({paths:e.paths,state:t});let r=await ee(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(fu(r).stateVersion!==r.stateVersion)return Wx({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ge(e.paths,hu(r,t))}let i=mx(t),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await mn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:n}),n})}async function iy(e){let t=await L(e.paths,e.name),r=await Yn(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await ee(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await hr.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=fu(n);if(i||a.stateVersion!==n.stateVersion){let o=await Wx({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await hr.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ge(e.paths,hu(n,t)),{state:t,action:"recorded-final-verification"}}async function ny(e){return $(e.paths,`recover Supervisor final verification ${e.name}`,()=>iy(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function Bx(e){return $(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Hi({paths:e.paths,state:t});let r=gx({state:t,summary:e.summary}),i=await gt({paths:e.paths,previous:t,next:r});return await we(ue(e.paths,t.name),Je({portableState:i,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await mn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:i}),i})}async function qx(e){return $(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Hi({paths:e.paths,state:t});let r=await ec({paths:e.paths,state:t}),i=wx(t,{reason:e.reason}),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),bu({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Fx(e){return $(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await ec({paths:e.paths,state:t}),i=Nx(t),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),bu({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function tc(e){return $(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=Qs({state:t,reason:e.reason}),i=await gt({paths:e.paths,previous:t,next:r});return await we(ue(e.paths,t.name),Je({portableState:i,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function Mx(e){return $(e.paths,`sync spec references ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(t.state_version!==e.expectedStateVersion)throw new Error("Native spec sync state version is stale");if(t.archived||!["build","verify","archive"].includes(t.phase)||t.children_contract_hash)throw new Error("Native spec sync requires a confirmed ordinary active change; revise requirements in Shape otherwise");if(!yu.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await Hi({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:v,operation:h})=>v===e.capability&&h!=="remove");if(!r?.source)throw new Error("Stage this capability in the current change and confirm Shape before syncing references");let i=new Set(e.affectedAcceptanceIds);if(i.size===0||[...i].some(v=>!t.acceptance.some(h=>h.id===v))||t.acceptance.some(({source:v,id:h})=>v===r.source&&!i.has(h)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:v,to:h})=>!/^[A-Za-z0-9_./#%-]+$/u.test(v)||!/^[A-Za-z0-9_./#%-]+$/u.test(h)||v===h)||new Set(e.replacements.map(({from:v})=>v)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=ye(e.paths,t.name),a=await re({root:n,ref:r.source,maxBytes:4*1024*1024,includeHash:!1}),o=new Map(e.replacements.map(({from:v,to:h})=>[v,h])),s=new Set,c=null,l=!1,u=a.text.split(/(?<=\n)/u).map(v=>{let h=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(v.trimEnd());return h?(c?h[1][0]===c.marker&&h[1].length>=c.length&&!h[2].trim()&&(c=null):c={marker:h[1][0],length:h[1].length},v):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(v)?v:(v.includes("<!--")&&(l=!0),l?(v.includes("-->")&&(l=!1),v):c||/^(?: {4}|\t)/u.test(v)||v.includes("`")?v:v.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(m,g,w)=>{let S=o.get(w);return S?(s.add(w),`[${g}](${S})`):m}))}).join("");if(s.size!==o.size)throw new Error("Native spec sync replacement is not an existing prose Markdown reference; use revise-requirements for semantic changes");let d=Ge.join(n,r.source);await xe(d,u,{containedRoot:e.paths.nativeRoot});let f=!1,p=null;try{let v=await Gh({paths:e.paths,state:t,specChanges:t.spec_changes});if(!Zv(t.acceptance,v.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let h=E=>u1("sha256").update(E).digest("hex"),m=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:h(a.text),afterHash:h(u),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=h(m),w=await Gs({paths:e.paths,name:t.name,hash:g,text:m,onCreated:()=>{p=g}}),S={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},N=t.phase==="build"?{...S,state_version:t.state_version+1,acceptance:t.acceptance.map(E=>i.has(E.id)?{...E,result:"pending",reason:null}:E)}:Qs({state:S,reason:`Spec reference sync: ${e.reason}`});N=Pt(N,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:ke(`Spec reference sync by ${e.actor}: ${e.reason}; ${w}`),completed_at:new Date().toISOString()}),N.shape_confirmation_hash=Uh({formalHash:v.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let y=await gt({paths:e.paths,previous:t,next:N});return f=!0,await we(ue(e.paths,t.name),Je({portableState:y,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),y}catch(v){if(!f)try{(await L(e.paths,t.name)).state_version===t.state_version&&(await xe(d,a.text,{containedRoot:e.paths.nativeRoot}),p&&await Sw({paths:e.paths,name:t.name,hash:p}))}catch{}throw v}})}async function Lx(e){if(!yu.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return $(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await L(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=t.spec_changes.filter(({capability:a})=>a!==e.capability),i={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...r,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Vx(e){return $(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await gt({paths:e.paths,previous:t,next:r});return await we(ue(e.paths,t.name),Je({portableState:i,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await mn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:i}),i})}async function rc(e){return $(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:ku({paths:e.paths,state:t,reason:e.reason})})}async function ku(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Pt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ke(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Wx(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...Pt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ke(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Kh(e){if(e.state.verification===null)return"not-applicable";let t=Ge.join(ye(e.paths,e.state.name),"verification.md");return await wu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await mn({file:t,state:e.state}),"rebuilt")}async function zx(e){let t=await L(e.paths,e.name),r=ue(e.paths,e.name);try{let i=await hi(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}fn();ai();no();Q();al();import{randomUUID as k1}from"crypto";import{promises as Su}from"fs";import Gx from"path";var ay="comet.selection.v2",S1=16*1024;function Eu(e){return Gx.join(e,".comet","current-change.json")}function E1(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Jx(e){return e===null||typeof e=="string"}function Ux(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!E1(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Jx(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ay,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ay)throw new Error(`current change selection schema must be ${ay}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Jx(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function oy(e){let t;try{let i=Eu(e),{bytes:n}=await Ja(i,S1,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Ux(t)}}async function Kx(e,t){let r=Ux(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Eu(e),n=`${i}.${k1()}.tmp`;await Su.mkdir(Gx.dirname(i),{recursive:!0});try{await Su.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
272
|
-
`,"utf8"),await Su.rename(n,i)}catch(a){throw await Su.rm(n,{force:!0}),a}}async function Yx(e){await Su.rm(Eu(e),{force:!0})}async function Xx(e,t,r){let i=await oy(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await Yx(e),!0)}Ee();tt();it();var JX=16*1024;async function Ru(e){let t=await oy(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(uo(t.selection.change),t.selection)}function Pu(e){return Eu(e.projectRoot)}async function Yh(e,t){return $(e,`select change ${t}`,async()=>{uo(t),await Be(e,t)?await L(e,t):await De(e,t),await Kx(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Qx(e){let t=await Ru(e);return t?(await Be(e,t.change)?await L(e,t.change):await De(e,t.change),t.change):null}async function Cu(e,t){return await cs(e.projectRoot),Xx(e.projectRoot,"native",t)}var Au=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function sy(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function cy(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=wt.join(e.archiveDir,t);if(!q(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function xu(e){try{return await At.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Zx(e,t){let r=wt.normalize(wt.resolve(e)),i=wt.normalize(wt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function eA(e,t){let r;try{r=await At.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=wt.join(e.archiveDir,n.name);try{let o=await Rt(wt.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function uy(e,t){let r=await Yn(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function tA(e,t){return await uy(e,t)!==null||await eA(e,t)!==null}async function _o(e,t){await At.mkdir(e.transactionsDir,{recursive:!0}),await fe(Kn(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function rA(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=kt(e.paths.projectRoot);r.some(a=>Zx(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await X(a);if(!o)continue;let s=await pe(a,o.native.artifact_root);i.some(c=>Zx(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await At.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Rt(wt.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await fo(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function P1(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function C1(e){let t=wt.join(e.paths.specsDir,e.change.capability),r=wt.join(t,"spec.md");if(!q(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await At.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await At.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([At.realpath(e.paths.specsDir),At.realpath(t)]);if(!q(o,s))throw new Error("Native canonical capability path escaped");try{let c=await At.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await At.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await At.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=wt.join(ye(e.paths,e.state.name),e.change.source);await xe(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await At.mkdir(t,{recursive:!0}),await xe(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function dy(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function x1(e,t){let r=ye(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await re({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function A1(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(dy(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function ly(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=wt.join(e.specsDir,i);if(r.operation==="remove"){if(!await xu(n))continue}else try{if((await re({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function fy(e){let t=await L(e.paths,e.name),r=[];try{dy(t)}catch(o){r.push(o.message)}let i=await uy(e.paths,e.name);if(i)try{await ly(e.paths,i)}catch(o){r.push(o.message)}if(i===null)try{let o=await Ao({paths:e.paths,state:t});o.drifted&&r.push(o.reason??"Native confirmed requirements changed")}catch(o){r.push(o.message)}let n=t.verification===null?"missing":await wu({file:wt.join(ye(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&r.push(`verification.md is ${n}`);let a=await rA({paths:e.paths,state:t});return a.length>0&&r.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:r.length===0,blockers:r,capabilityPeers:a,archiveDir:cy(e.paths,sy(t)),stateVersion:t.state_version}}async function _u(e){return $(e.paths,`archive portable change ${e.name}`,async()=>{let t=P1(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await uy(e.paths,e.name),i=ye(e.paths,e.name),n=await xu(i),a=n?null:await eA(e.paths,e.name),o;if(n)o=await L(e.paths,e.name);else if(r)o=await Rt(wt.join(cy(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await ee(e.paths,e.name);if(n&&!o.archived&&r===null){let f=await Ao({paths:e.paths,state:o});if(f.drifted){let p=f.reason??"Native confirmed requirements changed";throw await ku({paths:e.paths,state:o,reason:p}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await iy({paths:e.paths,name:e.name});if(o=f.state,f.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");f.action==="recorded-final-verification"&&(s=await ee(e.paths,e.name))}let c=cy(e.paths,r?.archive_ref??sy(o)),l=await xu(c);if(r&&A1(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Cu(e.paths,o.name),await At.rm(Oe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)dy(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await rA({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new Au(f);r={schema:Hf,id:R1(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:sy(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await x1(e.paths,o),created_at:new Date().toISOString()},await _o(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await _o(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await ly(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>wt.relative(e.paths.projectRoot,wt.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await pu({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),r.status==="prepared"){for(let f=r.next_spec_index;f<r.spec_changes.length;f+=1)await C1({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await _o(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await _o(e.paths,r)}if(await ly(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await pu({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),!o.archived){let f={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Gn({file:pr(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await _o(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await xu(i)?i:c;if(await mn({file:wt.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await wu({file:wt.join(f,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await _o(e.paths,r),s&&!d&&(await pu({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await pu({paths:e.paths,state:s,archiveOwnedPaths:u}),await At.mkdir(e.paths.archiveDir,{recursive:!0}),await xu(c))throw new Error(`Native Archive target already exists: ${c}`);await At.rename(i,c),r={...r,status:"moved"},await _o(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Cu(e.paths,o.name),await At.rm(Oe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await At.rm(Kn(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}us();function vn(e,t,r){return e.language==="zh-CN"?r:t}function _1(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:vn(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:vn(e,"Reply A or B","回复 A 或 B"),agentInstruction:vn(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(vn(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(vn(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(vn(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function I1(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function T1(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:vn(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:vn(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function nA(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Io(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function j1(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function iA(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function $1(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function O1(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Na(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:nA({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Io("summary","--summary"),j1(e.name,e.flag)]}}function hy(e){return[Na({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Na({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function K(e,t,r={}){let i=$1(t)&&e.coordination_mode===void 0,n=_1(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hy({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Na({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hy({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:hy({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?nA({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:O1({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[iA("coordination-mode","--coordination-mode",_f)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=t.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[Io("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${vn(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[iA("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...T1(e)],userCommunication:I1(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Na({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}zt();$e();Jt();Ee();it();og();no();Af();import{randomUUID as H1}from"node:crypto";import{promises as ic}from"node:fs";import dA from"node:path";ai();Q();Lr();var py=["evidence.md","repair.md","archive.md","checkpoint.md"],D1="verification.md";async function B1(e){try{return await ic.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function my(e,t){let r=se(e,t),i=[Kn(e,{kind:"migration",change:t}),Ka(e,t),...py.map(n=>dA.join(r,n))];return(await Promise.all(i.map(B1))).some(Boolean)}async function q1(e,t){let r=await Yn(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function aA(e,t){await ic.mkdir(e.transactionsDir,{recursive:!0}),await fe(Kn(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function oA(e,t,r={}){let i=r.removeVerificationReport===!1?py:[...py,D1];await Promise.all([ic.rm(Oe(e,t),{recursive:!0,force:!0}),ic.rm(Ka(e,t),{recursive:!0,force:!0}),...i.map(n=>ic.rm(dA.join(se(e,t),n),{force:!0}))])}async function sA(e,t){await we(ue(e,t.name),Je({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function cA(e,t){try{let r=await Dt(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function lA(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ne(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function F1(e){let t=se(e.paths,e.state.name),r=await re({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await re({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return xf({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function uA(e,t){let r=await fo(e,t);if(r.status==="runtime-incompatible")throw new ci(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function pi(e){return $(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await q1(e.paths,e.name),r=await Be(e.paths,e.name)?await Rt(pr(e.paths,e.name)):null;if(!t&&r)return await oA(e.paths,e.name,{removeVerificationReport:!1}),await sA(e.paths,r),r;let i=null,n=null;for(t||(i=await uA(e.paths,e.name),n=await cA(e.paths,e.name),lA(e.paths,n),t={schema:Of,id:H1(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await aA(e.paths,t));;){let a=$E(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await uA(e.paths,e.name),n??=await cA(e.paths,e.name),lA(e.paths,n),r=jE({state:i,acceptance:await F1({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await hs(pr(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await oA(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Rt(pr(e.paths,e.name)),await sA(e.paths,r)),t={...t,status:a.nextStatus},await aA(e.paths,t)}return await ic.rm(Kn(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Rt(pr(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}zt();import{promises as hA}from"node:fs";import pA from"node:path";it();ga();ct();fn();import{promises as vy}from"node:fs";import M1 from"node:path";var L1=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),V1=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),W1=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),z1=new Set(["status","summary"]);function Xh(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Qh(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function J1(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function To(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function G1(e,t,r,i){let n=Xh(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Qh(n,L1,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Xh(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Qh(o,V1,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Xh(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Qh(c,z1,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Xh(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:v,...h}=f,m=Qh(h,W1,`Native Supervisor child ${u}`);if(m)return m;let g=r.children[u],w=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||v!==void 0&&v!==D("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!J1(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let S=g.depends_on.length===0?"ready":"pending";if(f.status!==S)return`Native Supervisor child ${g.name} has progressed beyond its initial ${S} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function gn(e){let t=Ys(e.paths,e.state.name),r;try{let c=await vy.lstat(t);if(!c.isFile()||c.isSymbolicLink())return To(t,"","Native Supervisor overlay is not a regular file");r=await vy.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:To(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return To(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=M1.join(e.paths.changesDir,e.state.name),a;try{a=await $i({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return To(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await ee(e.paths,e.state.name)}catch(c){return To(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return To(t,r,"Native Supervisor overlay disappeared during inspection");let s=G1(i,e.state,a.contract,o);return s?To(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function fA(e){let t=await gn({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await vy.rm(t.file,{force:!1})}ai();gl();function gy(e,t){let r=ne(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function U1(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function K1(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Pt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ke(t),completed_at:i});return z({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?U1(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Y1(e){try{let t=await hi(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function jo(e){return $(e.paths,`recover portable change ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(t.status==="done")return await Kh({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=gy(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await gn({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await fA({paths:e.paths,state:t,expected:i}),n=!0);let a=ue(e.paths,e.name),o=await Y1(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await we(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Kh({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=Qs({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Gn({file:pr(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await hA.rm(pA.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Je({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await we(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=u||d;if(f){let v=K1(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Gn({file:pr(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let p=Je({portableState:t,projectRoot:e.paths.projectRoot,branch:ne(e.paths.projectRoot).currentBranch});return await hA.mkdir(pA.dirname(ue(e.paths,t.name)),{recursive:!0}),await we(a,p,{containedRoot:e.paths.runtimeDir}),await Kh({paths:e.paths,state:t}),{state:t,local:p,action:f?"reverify":"resume-stable-boundary",reason:s,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}no();kh();tn();zt();import{accessSync as iW,constants as nW,promises as aW}from"node:fs";import Di from"node:path";Ee();ho();Lr();kh();var X1=6e4,yt=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function wy(e,t){try{return nn("gh",t,{cwd:e,timeoutMs:X1}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function yy(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function Ny(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function mA(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function $o(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function vA(e,t){let r=$o(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function ep(e,t){let r=$o(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function gA(e,t){let r=yy(e,t);if($o(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:mA(r.number,`${t}.number`),url:vA(r.url,`${t}.url`),baseBranch:$o(r.baseRefName,`${t}.baseRefName`),headBranch:$o(r.headRefName,`${t}.headRefName`),headSha:ep(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function Q1(e){let t=yy(e,"pull request finish provider output.pullRequest");return{number:mA(t.number,"pull request finish provider output.pullRequest.number"),url:vA(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:$o(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:$o(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:ep(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function Z1(e){let t=yy(Ny(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=Q1(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function by(e){let t=wy(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Ny(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:gA(r[0],"gh pr list output[0]")}function wA(e){let t=wy(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=gA(Ny(t,"gh pr view output"),"gh pr view output"),i=ep(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new yt("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new yt(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new yt(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new yt(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Zh(e){try{return by(e)}catch{return null}}function eW(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function tW(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=wy(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=by(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new yt("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof yt)throw n;let a=Zh(e);if(!a)throw new yt(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=wA({...e,pullRequest:t})}catch(n){throw n instanceof yt?n:new yt(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function rW(e){let[t,...r]=e.config.command,i;try{let o=nn(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${eW(e)}
|
|
273
|
-
`}).trim();i=Z1(o)}catch(o){if(o instanceof yt)throw o;let s=Zh(e)??e.existingPullRequest;throw new yt(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==ep(e.headSha,"Native Archive head SHA")){let o=Zh(e)??e.existingPullRequest;throw new yt("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=wA({...e,pullRequest:n})}catch(o){if(o instanceof yt)throw o;let s=Zh(e)??e.existingPullRequest??n;throw new yt(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function yA(e){let t=by(e);return e.config?rW({...e,existingPullRequest:t,config:e.config}):tW({...e,existingPullRequest:t})}var Iu=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},wn=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function ky(e,t){let r=
|
|
271
|
+
`}function l1(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function wu(e){let t;try{t=await n1.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=l1(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function vn(e){await xe(e.file,c1(e.state,e.supervisor))}Q();Va();zr();tt();var yu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,d1="comet-state.yaml",f1="state.json",$X=Qc("en");function ya(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ye(e,t){if(!yu.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Ge.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function pr(e,t){return Ge.join(ye(e,t),d1)}function ue(e,t){return Ge.join(He(e,t),f1)}async function _e(e,t){try{let r=await hr.readFile(pr(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function h1(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function xt(e){return ne(e).currentBranch}function p1(e,t){if(!t)return;let r=ne(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Ex(e){return $(e.paths,`create portable change ${e.name}`,async()=>{if(!yu.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await X(e.paths.projectRoot)===null&&await Nr(e.paths.projectRoot,e.initialProjectConfig),p1(e.paths.projectRoot,e.workspaceBinding);let t=(await yP(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Is(e.workspaceBinding?.isolation??"current",t);let r=ye(e.paths,e.name),i=He(e.paths,e.name);await Promise.all([j(e.paths.nativeRoot,r),j(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await hr.mkdir(e.paths.changesDir,{recursive:!0}),await hr.mkdir(r,{recursive:!1}),n=!0,await hr.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await hr.mkdir(i,{recursive:!1}),a=!0,await hr.mkdir(Ge.join(r,"specs"),{recursive:!0}),await xe(Ge.join(r,"brief.md"),Qc(e.language));let o=ig({name:e.name,language:e.language,workspace:h1(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await hs(pr(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await we(ue(e.paths,e.name),Je({portableState:o,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await hr.rm(i,{recursive:!0,force:!0}),n&&await hr.rm(r,{recursive:!0,force:!0}),o}})}async function L(e,t){return Rt(pr(e,t))}async function gt(e){let t=await Gn({file:pr(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=Ge.join(ye(e.paths,t.name),"verification.md");await j(e.paths.nativeRoot,r),await hr.rm(r,{force:!0})}return t}async function ty(e){let t=ye(e.paths,e.state.name),r=Ge.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await hr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!yu.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Ge.join(t,...s.split("/")),l=await hr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Ge.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await hr.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Gh(e){let t=ye(e.paths,e.state.name),r=await re({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Vg(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await re({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:B("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:xf({briefMarkdown:r.text,specs:i}),formalHash:B("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:B("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function Uh(e){return B("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Rx(e){return $(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await ty({paths:e.paths,state:t}),i=await Gh({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Oi({changeDir:ye(e.paths,t.name),acceptanceIds:n.map(({id:d})=>d),validation:xo({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await mu(ye(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:Uh({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=dx({state:c,acceptance:n.map(d=>({...d}))});a&&(l.children_contract_hash=Xs({acceptance:l.acceptance,children:a.contract}));let u=await gt({paths:e.paths,previous:t,next:l});return await we(ue(e.paths,t.name),Je({portableState:u,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),u})}async function Px(e){return $(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await Di({paths:e.paths,state:t});let r=await ty({paths:e.paths,state:t}),i=await Gh({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Oi({changeDir:ye(e.paths,t.name),acceptanceIds:n.map(({id:h})=>h),validation:xo({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await mu(ye(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=Uh({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let h=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await ku({paths:e.paths,state:t,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}let l=ux({state:{...t,spec_changes:r},acceptance:n.map(h=>({...h}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Xs({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let h=[...t.history].reverse().find(({outcome:m})=>m==="pass"||m==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let m=await vt({paths:e.paths,state:l}),g=new Map((m?.children??[]).map(({name:N,status:y})=>[N,y])),w=new Set(a.contract.children.filter(({name:N})=>{let y=g.get(N);return y!=="done"&&y!=="integrated"&&y!=="archived"}).flatMap(({covers:N})=>N)),S=h.unresolved_ids.filter(N=>!w.has(N));if(S.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${S.join(", ")}`)}}let u=null,d=a?.contract.schema==="comet.native.children.v2"?await ee(e.paths,t.name):null,f=null,p=null;if(a?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.change_branch??t.workspace.target_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(p=yi(e.paths.projectRoot,f),!p)throw new Error(`Native Supervisor target branch has no commit: ${f}`);d||(d=await Hh({paths:e.paths,parent:t.name,targetBranch:f,contract:a.contract})),d||(u=await VC({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await X(e.paths.projectRoot)}))}let v=await gt({paths:e.paths,previous:t,next:l});if(await we(ue(e.paths,t.name),Je({portableState:v,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&f&&p){let h=d?JC({state:d,contract:a.contract}):u?Hw({parent:v.name,targetBranch:f,targetCommit:p,integrationBranch:u.binding.changeBranch,integrationWorktree:u.projectRoot,contract:a.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ge(e.paths,h)}return v})}async function Ao(e){let t=await ty(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Gh({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!Zv(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Oi({changeDir:ye(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:xo({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Uh({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Xs({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Di(e){let t=await Ao(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await ku({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Cx(e){return $(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(await Di({paths:e.paths,state:t}),await Oi({changeDir:ye(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:xo(t)})||t.children_contract_hash){let a=await vt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=fx({state:t,input:e.input}),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Nu(e){let t=await L(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await vt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}async function xx(e){let t=await zw({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await Nu({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}function ry(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:vh(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function Ax(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...ry(t,r,i),executionCount:e.executionCount}}function _x(e,t){let r=Ge.relative(Ge.resolve(e),Ge.resolve(t));if(Ge.isAbsolute(r)||r===".."||r.startsWith(`..${Ge.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(Ge.sep).join("/");return vh(e,i),i}function Zw(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Jl({id:e.id,name:e.id,executable:r,argv:i,cwdRef:_x(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function m1(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Zs(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:ke(i),argv_display:rw(r.argv.slice(1)).map(n=>ke(n)),argv_truncated:!1,cwd_ref:_x(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:m1(r)}})}function v1(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function bu(e){if(e.local===null||e.local.change!==e.state.name)return Je({portableState:e.state,projectRoot:e.projectRoot,branch:xt(e.projectRoot)});let t=e.local.execution?.operationId??ey();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function ec(e){try{let t=await pi(ue(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Ix(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function g1(e){let{state:t,local:r,envelope:i}=e;if(!wh(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function w1(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Jh(e){let t=await ec({paths:e.paths,state:e.state}),r=yx({state:e.state,summary:e.summary}),i=await gt({paths:e.paths,previous:e.state,next:r});return await we(ue(e.paths,e.state.name),bu({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Sx(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>Zw(i,r)===Jl(t[n]))}async function y1(e){return $(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(await Di({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=ue(e.paths,t.name),i=(await Qw({file:r,portableState:t,projectRoot:e.projectRoot,branch:xt(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Sx(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:u})=>[l,u]));return{kind:"reuse",state:t,checks:Zs({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Qs({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(u=>!u.repeatable).map(({id:u})=>u).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await gt({paths:e.paths,previous:t,next:c});throw await we(ue(e.paths,t.name),Je({portableState:l,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(u=>!u.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Sx(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=ey(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?Ax(s,o,n,e.projectRoot):s?{...s,operationId:n}:ry(o,n,e.projectRoot)})};return await we(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function Wh(e){return $(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await L(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=ue(e.paths,t.name),i=await pi(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await we(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Tx(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){la(t,c);let l=Jl(c);i.has(l)||(i.add(l),r.push(c))}let n=await y1({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=He(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Wh({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>f.id===c.id?{...f,status:"running",executionCount:f.executionCount+1,startedAt:l}:f)})});let u=await mo({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await Wh({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>f.id===c.id?{...f,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef}:f)})})}await Wh({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Wh({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)})})}catch{}throw c}let s=await pi(ue(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Zs({local:s,projectRoot:t,supplied:[]})}}async function N1(e){let t=ue(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Jw)throw new Error(`Native Verifier request-checks exceeded ${Jw} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let v=Zw(p,e.projectRoot);n.set(v,p),p.status!=="interrupted"&&i.set(v,p),a.set(p.id,v)}let o=new Map,s=new Map;for(let p of e.response.checks){let v=v1(p);la(e.projectRoot,v);let h=Jl(v),m=s.get(v.id);if(m!==void 0&&m!==h)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let g=a.get(v.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,v)}let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,d=new Map(c.map(([,p])=>[p.id,p.name])),f={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(p=>{let v=Zw(p,e.projectRoot),h=o.get(v);return h&&p.status==="interrupted"?Ax(p,h,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>ry(p,r.execution.operationId,e.projectRoot))]};return await we(t,f,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:f,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function zh(e){return $(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await L(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=ue(e.paths,t.name),i=await pi(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await we(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function b1(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await zh({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await mo({projectRoot:e.projectRoot,runtimeDir:He(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await zh({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await zh({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await zh({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Zs({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function jx(e){return $(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Di({paths:e.paths,state:t});let i=(await Qw({file:ue(e.paths,t.name),portableState:t,projectRoot:r,branch:xt(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Zs({local:i,projectRoot:r,supplied:e.checks});let n=hx(t),a=await gt({paths:e.paths,previous:t,next:n}),o=ue(e.paths,t.name),s=ey();return await we(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function $x(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await $(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await L(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Di({paths:e.paths,state:r});let n=await ec({paths:e.paths,state:r}),a=g1({state:r,local:n,envelope:e.envelope}),o;try{o=aw(a.payload)}catch(d){let f=`Native Verifier response was invalid: ${d.message}`,p=await Jh({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${vu} was recorded`,{cause:d})}let s=w1(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Zs({local:n,projectRoot:i,supplied:e.checks}));let d=px({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let f=await N1({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:f}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=d}catch(d){let f=`Native Verifier response was invalid: ${d.message}`,p=await Jh({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${vu} was recorded`,{cause:d})}let u=await gt({paths:e.paths,previous:r,next:l.state});return await we(ue(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?bu({local:n,state:u,projectRoot:i}):Je({portableState:u,projectRoot:i,branch:xt(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await vn({file:Ge.join(ye(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await b1({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await $(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await L(e.paths,e.name);return a.state_version!==t.state.state_version?null:Jh({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${vu} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Ox(e){return $(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await L(e.paths,e.name),r=await ec({paths:e.paths,state:t});if(Ix({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Jh({paths:e.paths,state:t,summary:e.summary})})}async function Hx(e){return $(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name);await Di({paths:e.paths,state:t});let r=await ec({paths:e.paths,state:t}),i=Ix({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Zs({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=vx({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await gt({paths:e.paths,previous:t,next:a});return await we(ue(e.paths,t.name),bu({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await vn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:o}),o})}async function Dx(e){return $(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Di({paths:e.paths,state:t});let r=await ee(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(fu(r).stateVersion!==r.stateVersion)return Wx({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ge(e.paths,hu(r,t))}let i=mx(t),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:n}),n})}async function iy(e){let t=await L(e.paths,e.name),r=await Yn(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await ee(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await hr.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=fu(n);if(i||a.stateVersion!==n.stateVersion){let o=await Wx({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await hr.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ge(e.paths,hu(n,t)),{state:t,action:"recorded-final-verification"}}async function ny(e){return $(e.paths,`recover Supervisor final verification ${e.name}`,()=>iy(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function Bx(e){return $(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Di({paths:e.paths,state:t});let r=gx({state:t,summary:e.summary}),i=await gt({paths:e.paths,previous:t,next:r});return await we(ue(e.paths,t.name),Je({portableState:i,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await vn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:i}),i})}async function qx(e){return $(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Di({paths:e.paths,state:t});let r=await ec({paths:e.paths,state:t}),i=wx(t,{reason:e.reason}),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),bu({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Fx(e){return $(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await L(e.paths,e.name);ya({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await ec({paths:e.paths,state:t}),i=Nx(t),n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),bu({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function tc(e){return $(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=Qs({state:t,reason:e.reason}),i=await gt({paths:e.paths,previous:t,next:r});return await we(ue(e.paths,t.name),Je({portableState:i,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function Mx(e){return $(e.paths,`sync spec references ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(t.state_version!==e.expectedStateVersion)throw new Error("Native spec sync state version is stale");if(t.archived||!["build","verify","archive"].includes(t.phase)||t.children_contract_hash)throw new Error("Native spec sync requires a confirmed ordinary active change; revise requirements in Shape otherwise");if(!yu.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await Di({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:v,operation:h})=>v===e.capability&&h!=="remove");if(!r?.source)throw new Error("Stage this capability in the current change and confirm Shape before syncing references");let i=new Set(e.affectedAcceptanceIds);if(i.size===0||[...i].some(v=>!t.acceptance.some(h=>h.id===v))||t.acceptance.some(({source:v,id:h})=>v===r.source&&!i.has(h)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:v,to:h})=>!/^[A-Za-z0-9_./#%-]+$/u.test(v)||!/^[A-Za-z0-9_./#%-]+$/u.test(h)||v===h)||new Set(e.replacements.map(({from:v})=>v)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=ye(e.paths,t.name),a=await re({root:n,ref:r.source,maxBytes:4*1024*1024,includeHash:!1}),o=new Map(e.replacements.map(({from:v,to:h})=>[v,h])),s=new Set,c=null,l=!1,u=a.text.split(/(?<=\n)/u).map(v=>{let h=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(v.trimEnd());return h?(c?h[1][0]===c.marker&&h[1].length>=c.length&&!h[2].trim()&&(c=null):c={marker:h[1][0],length:h[1].length},v):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(v)?v:(v.includes("<!--")&&(l=!0),l?(v.includes("-->")&&(l=!1),v):c||/^(?: {4}|\t)/u.test(v)||v.includes("`")?v:v.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(m,g,w)=>{let S=o.get(w);return S?(s.add(w),`[${g}](${S})`):m}))}).join("");if(s.size!==o.size)throw new Error("Native spec sync replacement is not an existing prose Markdown reference; use revise-requirements for semantic changes");let d=Ge.join(n,r.source);await xe(d,u,{containedRoot:e.paths.nativeRoot});let f=!1,p=null;try{let v=await Gh({paths:e.paths,state:t,specChanges:t.spec_changes});if(!Zv(t.acceptance,v.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let h=E=>u1("sha256").update(E).digest("hex"),m=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:h(a.text),afterHash:h(u),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=h(m),w=await Gs({paths:e.paths,name:t.name,hash:g,text:m,onCreated:()=>{p=g}}),S={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},N=t.phase==="build"?{...S,state_version:t.state_version+1,acceptance:t.acceptance.map(E=>i.has(E.id)?{...E,result:"pending",reason:null}:E)}:Qs({state:S,reason:`Spec reference sync: ${e.reason}`});N=Pt(N,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:ke(`Spec reference sync by ${e.actor}: ${e.reason}; ${w}`),completed_at:new Date().toISOString()}),N.shape_confirmation_hash=Uh({formalHash:v.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let y=await gt({paths:e.paths,previous:t,next:N});return f=!0,await we(ue(e.paths,t.name),Je({portableState:y,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),y}catch(v){if(!f)try{(await L(e.paths,t.name)).state_version===t.state_version&&(await xe(d,a.text,{containedRoot:e.paths.nativeRoot}),p&&await Sw({paths:e.paths,name:t.name,hash:p}))}catch{}throw v}})}async function Lx(e){if(!yu.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return $(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await L(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=t.spec_changes.filter(({capability:a})=>a!==e.capability),i={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...r,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Vx(e){return $(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await gt({paths:e.paths,previous:t,next:r});return await we(ue(e.paths,t.name),Je({portableState:i,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await vn({file:Ge.join(ye(e.paths,t.name),"verification.md"),state:i}),i})}async function rc(e){return $(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await L(e.paths,e.name);if(ya({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:ku({paths:e.paths,state:t,reason:e.reason})})}async function ku(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Pt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ke(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Wx(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...Pt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ke(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await gt({paths:e.paths,previous:t,next:i});return await we(ue(e.paths,t.name),Je({portableState:n,projectRoot:e.paths.projectRoot,branch:xt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Kh(e){if(e.state.verification===null)return"not-applicable";let t=Ge.join(ye(e.paths,e.state.name),"verification.md");return await wu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await vn({file:t,state:e.state}),"rebuilt")}async function zx(e){let t=await L(e.paths,e.name),r=ue(e.paths,e.name);try{let i=await pi(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}hn();oi();no();Q();al();import{randomUUID as k1}from"crypto";import{promises as Su}from"fs";import Gx from"path";var ay="comet.selection.v2",S1=16*1024;function Eu(e){return Gx.join(e,".comet","current-change.json")}function E1(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Jx(e){return e===null||typeof e=="string"}function Ux(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!E1(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Jx(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ay,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ay)throw new Error(`current change selection schema must be ${ay}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Jx(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function oy(e){let t;try{let i=Eu(e),{bytes:n}=await Ja(i,S1,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...Ux(t)}}async function Kx(e,t){let r=Ux(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Eu(e),n=`${i}.${k1()}.tmp`;await Su.mkdir(Gx.dirname(i),{recursive:!0});try{await Su.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
272
|
+
`,"utf8"),await Su.rename(n,i)}catch(a){throw await Su.rm(n,{force:!0}),a}}async function Yx(e){await Su.rm(Eu(e),{force:!0})}async function Xx(e,t,r){let i=await oy(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await Yx(e),!0)}Ee();tt();it();var JX=16*1024;async function Ru(e){let t=await oy(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(uo(t.selection.change),t.selection)}function Pu(e){return Eu(e.projectRoot)}async function Yh(e,t){return $(e,`select change ${t}`,async()=>{uo(t),await _e(e,t)?await L(e,t):await Be(e,t),await Kx(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Qx(e){let t=await Ru(e);return t?(await _e(e,t.change)?await L(e,t.change):await Be(e,t.change),t.change):null}async function Cu(e,t){return await cs(e.projectRoot),Xx(e.projectRoot,"native",t)}var Au=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function sy(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function cy(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=wt.join(e.archiveDir,t);if(!q(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function xu(e){try{return await At.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Zx(e,t){let r=wt.normalize(wt.resolve(e)),i=wt.normalize(wt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function eA(e,t){let r;try{r=await At.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=wt.join(e.archiveDir,n.name);try{let o=await Rt(wt.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function uy(e,t){let r=await Yn(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function tA(e,t){return await uy(e,t)!==null||await eA(e,t)!==null}async function _o(e,t){await At.mkdir(e.transactionsDir,{recursive:!0}),await fe(Kn(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function rA(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=kt(e.paths.projectRoot);r.some(a=>Zx(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await X(a);if(!o)continue;let s=await pe(a,o.native.artifact_root);i.some(c=>Zx(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await At.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Rt(wt.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await fo(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function P1(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function C1(e){let t=wt.join(e.paths.specsDir,e.change.capability),r=wt.join(t,"spec.md");if(!q(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await At.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await At.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([At.realpath(e.paths.specsDir),At.realpath(t)]);if(!q(o,s))throw new Error("Native canonical capability path escaped");try{let c=await At.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await At.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await At.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=wt.join(ye(e.paths,e.state.name),e.change.source);await xe(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await At.mkdir(t,{recursive:!0}),await xe(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function dy(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function x1(e,t){let r=ye(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await re({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function A1(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(dy(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function ly(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=wt.join(e.specsDir,i);if(r.operation==="remove"){if(!await xu(n))continue}else try{if((await re({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function fy(e){let t=await L(e.paths,e.name),r=[];try{dy(t)}catch(o){r.push(o.message)}let i=await uy(e.paths,e.name);if(i)try{await ly(e.paths,i)}catch(o){r.push(o.message)}if(i===null)try{let o=await Ao({paths:e.paths,state:t});o.drifted&&r.push(o.reason??"Native confirmed requirements changed")}catch(o){r.push(o.message)}let n=t.verification===null?"missing":await wu({file:wt.join(ye(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&r.push(`verification.md is ${n}`);let a=await rA({paths:e.paths,state:t});return a.length>0&&r.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:r.length===0,blockers:r,capabilityPeers:a,archiveDir:cy(e.paths,sy(t)),stateVersion:t.state_version}}async function _u(e){return $(e.paths,`archive portable change ${e.name}`,async()=>{let t=P1(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await uy(e.paths,e.name),i=ye(e.paths,e.name),n=await xu(i),a=n?null:await eA(e.paths,e.name),o;if(n)o=await L(e.paths,e.name);else if(r)o=await Rt(wt.join(cy(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await ee(e.paths,e.name);if(n&&!o.archived&&r===null){let f=await Ao({paths:e.paths,state:o});if(f.drifted){let p=f.reason??"Native confirmed requirements changed";throw await ku({paths:e.paths,state:o,reason:p}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await iy({paths:e.paths,name:e.name});if(o=f.state,f.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");f.action==="recorded-final-verification"&&(s=await ee(e.paths,e.name))}let c=cy(e.paths,r?.archive_ref??sy(o)),l=await xu(c);if(r&&A1(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Cu(e.paths,o.name),await At.rm(He(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)dy(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await rA({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new Au(f);r={schema:Hf,id:R1(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:sy(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await x1(e.paths,o),created_at:new Date().toISOString()},await _o(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await _o(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await ly(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>wt.relative(e.paths.projectRoot,wt.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await pu({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),r.status==="prepared"){for(let f=r.next_spec_index;f<r.spec_changes.length;f+=1)await C1({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await _o(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await _o(e.paths,r)}if(await ly(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await pu({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),!o.archived){let f={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Gn({file:pr(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await _o(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await xu(i)?i:c;if(await vn({file:wt.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await wu({file:wt.join(f,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await _o(e.paths,r),s&&!d&&(await pu({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await pu({paths:e.paths,state:s,archiveOwnedPaths:u}),await At.mkdir(e.paths.archiveDir,{recursive:!0}),await xu(c))throw new Error(`Native Archive target already exists: ${c}`);await At.rename(i,c),r={...r,status:"moved"},await _o(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Cu(e.paths,o.name),await At.rm(He(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await At.rm(Kn(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}us();function Jr(e,t,r){return e.language==="zh-CN"?r:t}function _1(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Jr(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Jr(e,"Reply A or B","回复 A 或 B"),agentInstruction:Jr(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Jr(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(Jr(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{required:!0,message:Jr(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:Jr(e,"Accept the result","接受结果"),agentInstruction:Jr(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")}:r(Jr(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function I1(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function T1(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:Jr(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Jr(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function nA(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Io(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function j1(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function iA(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function $1(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function O1(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Na(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:nA({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Io("summary","--summary"),j1(e.name,e.flag)]}}function hy(e){return[Na({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Na({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function U(e,t,r={}){let i=$1(t)&&e.coordination_mode===void 0,n=_1(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...hy({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Na({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:[Na({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...hy({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Io("summary","--summary")],commandAlternatives:hy({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?nA({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:O1({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[iA("coordination-mode","--coordination-mode",_f)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=t.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[Io("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Jr(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[iA("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...T1(e)],userCommunication:I1(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Na({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}zt();Oe();Jt();Ee();it();og();no();Af();import{randomUUID as H1}from"node:crypto";import{promises as ic}from"node:fs";import dA from"node:path";oi();Q();Lr();var py=["evidence.md","repair.md","archive.md","checkpoint.md"],D1="verification.md";async function B1(e){try{return await ic.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function my(e,t){let r=se(e,t),i=[Kn(e,{kind:"migration",change:t}),Ka(e,t),...py.map(n=>dA.join(r,n))];return(await Promise.all(i.map(B1))).some(Boolean)}async function q1(e,t){let r=await Yn(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function aA(e,t){await ic.mkdir(e.transactionsDir,{recursive:!0}),await fe(Kn(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function oA(e,t,r={}){let i=r.removeVerificationReport===!1?py:[...py,D1];await Promise.all([ic.rm(He(e,t),{recursive:!0,force:!0}),ic.rm(Ka(e,t),{recursive:!0,force:!0}),...i.map(n=>ic.rm(dA.join(se(e,t),n),{force:!0}))])}async function sA(e,t){await we(ue(e,t.name),Je({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function cA(e,t){try{let r=await Dt(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function lA(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ne(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function F1(e){let t=se(e.paths,e.state.name),r=await re({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await re({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return xf({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function uA(e,t){let r=await fo(e,t);if(r.status==="runtime-incompatible")throw new li(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function mi(e){return $(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await q1(e.paths,e.name),r=await _e(e.paths,e.name)?await Rt(pr(e.paths,e.name)):null;if(!t&&r)return await oA(e.paths,e.name,{removeVerificationReport:!1}),await sA(e.paths,r),r;let i=null,n=null;for(t||(i=await uA(e.paths,e.name),n=await cA(e.paths,e.name),lA(e.paths,n),t={schema:Of,id:H1(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await aA(e.paths,t));;){let a=$E(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await uA(e.paths,e.name),n??=await cA(e.paths,e.name),lA(e.paths,n),r=jE({state:i,acceptance:await F1({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await hs(pr(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await oA(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Rt(pr(e.paths,e.name)),await sA(e.paths,r)),t={...t,status:a.nextStatus},await aA(e.paths,t)}return await ic.rm(Kn(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Rt(pr(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}zt();import{promises as hA}from"node:fs";import pA from"node:path";it();ga();ct();hn();import{promises as vy}from"node:fs";import M1 from"node:path";var L1=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),V1=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),W1=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),z1=new Set(["status","summary"]);function Xh(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Qh(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function J1(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function To(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function G1(e,t,r,i){let n=Xh(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Qh(n,L1,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Xh(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Qh(o,V1,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Xh(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Qh(c,z1,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Xh(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:v,...h}=f,m=Qh(h,W1,`Native Supervisor child ${u}`);if(m)return m;let g=r.children[u],w=g.covers.length>0?g.covers.map(N=>({id:N,source:r.acceptance_index?.[N]?.source??"brief.md",text:r.acceptance_index?.[N]?.text??N})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||v!==void 0&&v!==B("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!J1(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let S=g.depends_on.length===0?"ready":"pending";if(f.status!==S)return`Native Supervisor child ${g.name} has progressed beyond its initial ${S} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function gn(e){let t=Ys(e.paths,e.state.name),r;try{let c=await vy.lstat(t);if(!c.isFile()||c.isSymbolicLink())return To(t,"","Native Supervisor overlay is not a regular file");r=await vy.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:To(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return To(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=M1.join(e.paths.changesDir,e.state.name),a;try{a=await Oi({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return To(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await ee(e.paths,e.state.name)}catch(c){return To(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return To(t,r,"Native Supervisor overlay disappeared during inspection");let s=G1(i,e.state,a.contract,o);return s?To(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function fA(e){let t=await gn({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await vy.rm(t.file,{force:!1})}oi();gl();function gy(e,t){let r=ne(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function U1(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function K1(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Pt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ke(t),completed_at:i});return z({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?U1(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Y1(e){try{let t=await pi(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function jo(e){return $(e.paths,`recover portable change ${e.name}`,async()=>{let t=await L(e.paths,e.name);if(t.status==="done")return await Kh({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=gy(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await gn({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await fA({paths:e.paths,state:t,expected:i}),n=!0);let a=ue(e.paths,e.name),o=await Y1(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await we(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Kh({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=Qs({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Gn({file:pr(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await hA.rm(pA.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=Je({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await we(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=u||d;if(f){let v=K1(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Gn({file:pr(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let p=Je({portableState:t,projectRoot:e.paths.projectRoot,branch:ne(e.paths.projectRoot).currentBranch});return await hA.mkdir(pA.dirname(ue(e.paths,t.name)),{recursive:!0}),await we(a,p,{containedRoot:e.paths.runtimeDir}),await Kh({paths:e.paths,state:t}),{state:t,local:p,action:f?"reverify":"resume-stable-boundary",reason:s,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}no();kh();rn();zt();import{accessSync as iW,constants as nW,promises as aW}from"node:fs";import Bi from"node:path";Ee();ho();Lr();kh();var X1=6e4,yt=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function wy(e,t){try{return an("gh",t,{cwd:e,timeoutMs:X1}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function yy(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function Ny(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function mA(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function $o(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function vA(e,t){let r=$o(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function ep(e,t){let r=$o(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function gA(e,t){let r=yy(e,t);if($o(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:mA(r.number,`${t}.number`),url:vA(r.url,`${t}.url`),baseBranch:$o(r.baseRefName,`${t}.baseRefName`),headBranch:$o(r.headRefName,`${t}.headRefName`),headSha:ep(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function Q1(e){let t=yy(e,"pull request finish provider output.pullRequest");return{number:mA(t.number,"pull request finish provider output.pullRequest.number"),url:vA(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:$o(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:$o(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:ep(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function Z1(e){let t=yy(Ny(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=Q1(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function by(e){let t=wy(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Ny(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:gA(r[0],"gh pr list output[0]")}function wA(e){let t=wy(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=gA(Ny(t,"gh pr view output"),"gh pr view output"),i=ep(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new yt("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new yt(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new yt(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new yt(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Zh(e){try{return by(e)}catch{return null}}function eW(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function tW(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=wy(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=by(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new yt("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof yt)throw n;let a=Zh(e);if(!a)throw new yt(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=wA({...e,pullRequest:t})}catch(n){throw n instanceof yt?n:new yt(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function rW(e){let[t,...r]=e.config.command,i;try{let o=an(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${eW(e)}
|
|
273
|
+
`}).trim();i=Z1(o)}catch(o){if(o instanceof yt)throw o;let s=Zh(e)??e.existingPullRequest;throw new yt(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==ep(e.headSha,"Native Archive head SHA")){let o=Zh(e)??e.existingPullRequest;throw new yt("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=wA({...e,pullRequest:n})}catch(o){if(o instanceof yt)throw o;let s=Zh(e)??e.existingPullRequest??n;throw new yt(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function yA(e){let t=by(e);return e.config?rW({...e,existingPullRequest:t,config:e.config}):tW({...e,existingPullRequest:t})}var Iu=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},wn=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function ky(e,t){let r=Bi.relative(e,t);return r===""||!Bi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Bi.sep}`)}function ba(e,t){let r=Bi.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||Bi.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function SA(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function NA(e,t,r,i=[]){let n=[...Hs(e.projectRoot)?[".comet/config.yaml"]:[],ba(e.projectRoot,se(e,t.name)),ba(e.projectRoot,Pu(e))];r&&n.push(ba(e.projectRoot,r));for(let a of r?t.spec_changes:i)n.push(ba(e.projectRoot,ca(e,a.capability)));return n}function bA(e,t){let r=Os(e).filter(i=>!SA(i,t));if(r.length>0)throw new wn(r,e)}function oW(e,t){return t.map(r=>Bi.resolve(e,...r.split("/")))}function sW(e){let t=Os(e).filter(r=>!(r===".comet/config.yaml"&&Hs(e)));if(t.length>0)throw new wn(oW(e,t),e,`Native merge target worktree is not clean: ${e}`)}function EA(e){return e.split("\0").filter(Boolean)}function cW(e,t){return EA(A(e,["ls-files","-z","--",t]))}function lW(e,t){return EA(A(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function kA(e){try{if(A(e,["config","--get","user.name"])&&A(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function uW(e,t){for(let r of kt(e))if(ne(r).currentBranch===t)return r;return null}function dW(e,t){try{an(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function fW(e,t){if(!t)return;let r=t.command[0];try{if(Bi.posix.isAbsolute(r)||Bi.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=Bi.resolve(e,r);if(!ky(e,n))throw new Error("configured executable escapes the project root");iW(n,nW.X_OK);return}an(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(i){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:i})}}async function tp(e){let{paths:t,state:r}=e,i=r.workspace,n=ne(t.projectRoot);if(i.isolation==="current"){if(!n.isGitWorktree)return null;if(!n.primaryWorktreeRoot||!n.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");kA(t.projectRoot);let c=NA(t,r,e.archiveDir,e.appliedSpecChanges);return bA(t.projectRoot,c),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:n.currentBranch,targetBranch:n.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!i.finish||!i.change_branch||!i.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(i.change_branch===i.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!n.primaryWorktreeRoot||n.currentBranch!==i.change_branch)throw new Error(`Native workspace finish requires branch ${i.change_branch} in the current registered worktree`);kA(t.projectRoot);let a=NA(t,r,e.archiveDir,e.appliedSpecChanges);bA(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:uW(n.primaryWorktreeRoot,i.target_branch);if(i.finish==="merge"&&i.isolation==="worktree"){if(!o)throw new Error(`Native merge finish requires a registered worktree on target branch ${i.target_branch}`);sW(o)}let s=i.finish==="push"||i.finish==="pull-request"?CP(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(dW("gh",["--version"]),fW(t.projectRoot,e.pullRequestFinish)),{finish:i.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:i.change_branch,targetBranch:i.target_branch,targetRoot:o,remote:s,isolation:i.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function hW(e){try{return await aW.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function pW(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},blockedPaths:[],message:null,recoveryArgs:null}}async function mW(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(ky(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await Wl(e.changeRoot),A(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function RA(e){let t=pW(e.plan),r=null;try{let i=[ba(e.paths.projectRoot,se(e.paths,e.name)),ba(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>ba(e.paths.projectRoot,ca(e.paths,l.capability))),ba(e.paths.projectRoot,Pu(e.paths))],n=Os(e.plan.changeRoot).filter(l=>!SA(l,i)&&!(l===".comet/config.yaml"&&Hs(e.plan.changeRoot)));if(n.length>0)throw t.blockedPaths=n,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.join(", ")}`);let a=[],o=new Set;for(let l of i){let u=Bi.resolve(e.paths.projectRoot,...l.split("/"));if(cW(e.plan.changeRoot,l).length>0&&a.push(l),await hW(u))for(let f of lW(e.plan.changeRoot,l))o.add(f)}if(a.length>0&&A(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&A(e.plan.changeRoot,["add","--",...o]),A(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&A(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=A(e.plan.changeRoot,["rev-parse","HEAD"]),!Er(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){A(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=yA({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url);let l=ky(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(await Wl(e.plan.changeRoot),A(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let c=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(A(c,["switch",e.plan.targetBranch]),r=c),A(c,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=c,t.cleanup=await mW(e.plan),t}catch(i){if(i instanceof yt&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{A(r,["merge","--abort"])}catch{}try{ne(r).currentBranch===e.plan.targetBranch&&A(r,["switch",e.plan.changeBranch]),n=ne(r).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=r)}throw t.status="blocked",t.message=i.message,t.recoveryArgs=e.plan.finish==="pull-request"?["comet","native","archive",e.name,"--confirmed"]:e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new Iu(t)}}al();import Fu from"path";import{realpathSync as Gz}from"fs";function Sy(e){return e.charCodeAt(0)===65279?e.slice(1):e}zt();var yn={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function PA(e){return e?e.command?`${yn.next} ${e.command}`:e.ask_user?`${yn.next} ${e.ask_user}`:null:null}function CA(e,t){let r=[e.summary],i=PA(e.next);return i&&r.push(i),e.user_message&&r.push("",yn.relay,e.user_message),t!==void 0&&r.push("",yn.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
274
274
|
`)}
|
|
275
275
|
`}function xA(e,t,r){let i=[e.summary],n=PA(e.next);return n&&i.push(n),e.user_message&&i.push("",yn.relay,e.user_message),i.push("",`${yn.detail} ${t}`),r!==void 0&&i.push("",yn.details,JSON.stringify(r,null,2)),i.join(`
|
|
276
|
-
`)}import{promises as K_}from"fs";import dc from"path";import{isDeepStrictEqual as Iz}from"util";import{createHash as vW}from"crypto";function AA(e,t,r,i){return t.iteration>=r.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${r.maxIterations}`}:e.type==="invoke_skill"&&!r.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!r.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!r.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&r.confirmationRequiredFor.includes(e.ref)&&!i.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>r.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function _A(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))_A(e[t]);return Object.freeze(e)}function ka(e){return _A(structuredClone(e))}function Ey(e,t,r,i){return e.resolveStep({pkg:ka(t),state:ka(r),context:ka(i)})}function IA(e,t,r,i,n,a){return e.resolveNext({pkg:ka(t),state:ka(r),step:ka(i),outcome:ka(n),context:ka(a)})}function gW(e,t,r){return vW("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function Ry(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function TA(e,t,r,i,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Ey(i,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Ry(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:gW(s.runId,s.iteration,o.id),stepId:o.id};return wW(e,s,c,r)}function wW(e,t,r,i){let n=AA(r,t,e.guardrails,i);return n.allowed?{state:{...t,pending:r.id,status:"waiting"},action:r}:{state:t,action:null,reason:n.reason}}function jA(e,t,r,i,n){if(!t.pending||t.pending!==r.actionId)throw new Error(`Outcome does not match pending action: ${r.actionId}`);let a=t.orchestration==="deterministic"?Ey(i,e,t,n):void 0,o=a?Ry(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(r.status==="failed"){let c={...t.retries,[r.actionId]:(t.retries[r.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?IA(i,e,t,o,r,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Ry(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}Zi();import{promises as az}from"node:fs";import $_ from"node:path";ct();import $A from"node:path";var yW="comet.native.archive-preflight.v1",NW="comet.native.archive-preflight.v1",bW="comet.native.archive-operation.v1",kW=/^[a-f0-9]{64}$/u,OA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SW=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function rp(e,t){return e<t?-1:e>t?1:0}function EW(e,t){if(typeof e!="string"||!kW.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Nn(e,t){return e===null?null:EW(e,t)}function RW(e,t){let r=$A.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||$A.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function PW(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function CW(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function xW(e,t){if(!OA.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=Nn(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=Nn(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Nn(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function AW(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Nn(e.contractHash,"Native archive contract hash"),acceptanceHash:Nn(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Nn(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Nn(e.reportHash,"Native archive report hash"),envelopeHash:Nn(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Nn(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function _W(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!SW.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(rp);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function IW(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(rp)}function HA(e){if(!OA.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(xW).sort((l,u)=>rp(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:D(bW,l)})),i=AW(e.evidence),n=CW(e.workspace),a=[...new Set([..._W(e.findingCodes??[]),...IW({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(rp),o=PW(e.revision),s=RW(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:yW,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:D(NW,c)}}Jt();Ee();ct();import{createHash as TW}from"node:crypto";import DA from"node:path";var jW="comet.native.conflict-radar.v1",mr=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}),$W="comet.native.conflict-radar.v1",OW="comet.native.conflict-radar-signals.v1",HW=/^[a-f0-9]{64}$/u,FA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DW=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),BW=new Set(["capability","operation","baseHash"]),qW=new Set(["path","kind"]);function nc(e,t){return e<t?-1:e>t?1:0}function Py(e){return Buffer.byteLength(e,"utf8")}function Cy(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function xy(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Py(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function FW(e,t){let r=xy(e,t,mr.maxArtifactPathBytes),i=DA.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||DA.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function MA(e,t){if(typeof e!="string"||!HW.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MW(e,t){let r=Cy(e,BW,t),i=xy(r.capability,`${t} capability`,mr.maxCapabilityBytes);if(!FA.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:MA(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function LW(e,t){let r=Cy(e,qW,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:FW(r.path,`${t} path`),kind:r.kind}}function VW(e,t){let r=Cy(e,DW,`Conflict radar change ${t}`),i=xy(r.name,`Conflict radar change ${t} name`,mr.maxNameBytes);if(!FA.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>mr.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>mr.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>MW(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>nc(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>LW(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>nc(c.path,l.path)||nc(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:MA(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function WW(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>mr.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(VW).sort((n,a)=>nc(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>mr.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>mr.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function zW(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function JW(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function GW(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function UW(e,t){let r=[],i=TW("sha256").update(`${OW}
|
|
277
|
-
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(dl(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<mr.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(zW(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=JW(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:GW(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function BA(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function KW(e,t){return BA(e.classification)-BA(t.classification)||nc(e.left,t.left)||nc(e.right,t.right)}function qA(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:jW,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function LA(e){let t=WW(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(UW(t[s],t[c]));r.sort(KW);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D($W,{changes:t,relationships:i}),a=r.slice(0,mr.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=qA(t,r,a,n);for(;a.length>0&&Py(JSON.stringify(o))>mr.maxSerializedBytes;)a=a.slice(0,-1),o=qA(t,r,a,n);if(Py(JSON.stringify(o))>mr.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}zr();Yt();Lr();var YW=4096;async function XW(e,t=mr.maxChanges){try{let r=await lr({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function VA(e,t){let r=await De(e,t),[i,n]=await Promise.all([r.implementation_scope?Us(e,t,r.implementation_scope):null,Dt(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ip(e,t,r={}){let n=(await XW(e,YW)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await VA(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await VA(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=LA([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}Ee();tt();Q();Ps();$e();Ee();qr();Qa();it();Q();Yt();rn();import{promises as p2}from"fs";import m2 from"path";import{isDeepStrictEqual as op}from"util";ct();ct();var ac={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var QW=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function ZW(e,t){return e<t?-1:e>t?1:0}function e2(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!QW.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(ZW)}function Ay(e=[]){return e2(e,"Native repair failed check IDs",ac.maxFailedCheckIds,!0)}function WA(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function t2(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:WA(e.failedAcceptanceIds,t.failedAcceptanceIds)&&WA(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function _y(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(t2(i,a))break;r+=1,i=a}return r}au();on();function np(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var zA="repairStagnation",Cr={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},i2=/^[a-f0-9]{64}$/u;var n2=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),a2=["data","runId","sequence","timestamp","type"],JA=["disposition","overrideSummaryHash","signatureHash"],o2=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],GA=12;function Ty(e,t){return e<t?-1:e>t?1:0}function UA(e,t,r){let i=Object.keys(e).sort(Ty);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function ap(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Tu(e,t){if(typeof e!="string"||!i2.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function s2(e){if(!Array.isArray(e)||e.length>ac.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Ty)}function KA(e){if(typeof e!="string"||e.length===0||e.length>Cr.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Iy(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Cr.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Cr.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Cr.maxTextCharacters&&(!n||e.length>Cr.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Cr.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Cr.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Iy(s,t+1,r,`${i}[${c}]`));return}let a=ap(e,i),o=Object.keys(a);if(o.length>Cr.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Cr.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Cr.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Iy(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function c2(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function l2(e,t,r){let i=ap(e,`Native repair trajectory event ${t+1}`);if(UA(i,a2,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(c2(i.timestamp),typeof i.type!="string"||!n2.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(KA(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Iy(i.data,0,n,"Native trajectory event data"),ap(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function jy(e){let t=ap(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Ty),i=r.length===JA.length&&r.every((l,u)=>l===JA[u]);i||UA(t,o2,"Native repair trajectory projection");let n=Tu(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Tu(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Tu(t.contractHash,"Native repair trajectory contract hash"),s=s2(t.failedAcceptanceIds),c=Ay(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function u2(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function d2(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??GA;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=_y({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<ac.warningAtConsecutiveFailures?"continue":a<ac.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function f2(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??GA;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function YA(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Cr.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=KA(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=l2(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Cr.maxTotalDataNodes||c>Cr.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Tu(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Tu(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,zA)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=jy(f[zA]);if(u2(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(r.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),d2(v,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");f2(v,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(i=v,r.length>ac.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function XA(e){return YA(e).history}function QA(e){let t=YA(e).latestProjection;return t?{...t}:null}qr();var Bi={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:[]},ju=G("comet-native-runtime:v3:scope-reopen"),h2=[{skillVersion:"3",skillHash:G("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function ZA(e){return e.skillVersion===Bi.definition.metadata.version&&e.skillHash===ju||h2.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var $y={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(r=>r.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};Zi();qr();Zi();async function Sa(e){let r={sequence:(await Zt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await GR(e.changeDir,e.run.trajectoryRef,r),r}async function Oo(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:G(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await UR(e.changeDir,e.run.checkpointRef,t),t}qr();function e_(e){return G(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}Il();wl();var c_=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],v2=new Set(c_),l_=new Set([...c_,"minimum_runtime_version","revision"]),g2=new Set([...l_,"operation"]),w2=512*1024,Oy=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),y2=new Set([...Oy,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),$u=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Mt(e,t){return m2.join(V(e,t),"transition.json")}function N2(e){return`transition-${e}`}async function b2(e,t,r){let i=N2(t);return Ui(e,i,r)}async function Fi(e,t,r,i){let n=await b2(e,t,r);try{return await i()}finally{await Ki(n)}}function cp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Dy(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function sp(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qi(e,t){return op(e,t)}function Hy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!y2.has(u)),a=[...Oy].find(u=>!Object.hasOwn(r,u)),o=Oy.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(np(r.summary,"Native transition journal event summary"),mt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(np(r.noCodeReason,"Native transition journal event no-code reason"),mt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?jy(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function k2(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Hy({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Hy(e,t)}function By(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?k2(e.eventData,e.evidenceHash):Hy(e.eventData,e.evidenceHash),n=oa(e.nextRun),a=e.previousRun===null?null:oa(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function t_(e,t,r=!1){if(e.skill!==Bi.definition.metadata.name||(r?!ZA(e):e.skillVersion!==Bi.definition.metadata.version||e.skillHash!==ju)||e.orchestration!==Bi.definition.orchestration.mode||e.pendingRef!==kr.pendingRef||e.trajectoryRef!==kr.trajectoryRef||e.contextRef!==kr.contextRef||e.artifactsRef!==kr.artifactsRef||e.checkpointRef!==kr.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function r_(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function i_(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function qy(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(t_(o,"next Run",i||a!==null),i_(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(t_(a,"previous Run",!0),i_(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!op(r_(a),r_(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function S2(e,t,r){return G(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function u_(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function n_(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Fy(e,t,r,i,n=!1){let a=r.eventData,o=n_(e),s=n_(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&op(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&op(e.spec_changes,t.spec_changes),l=e_({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.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(i==="spec-rebase"){let c=S2(e.name,a.summary,t.spec_changes),l=G(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function My(e,t){let r=cp(e);if(Dy(r,g2),r.schema!==Un)throw new Error(`Expected Native transition schema ${Un}`);let i=sp(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Un} minimum_runtime_version must be ${3}`);let n=sp(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=By(r,t),o=cr(r.previousState),s=cr(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Fy(o,s,a,r.operation),qy(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Un,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function E2(e,t){let r=cp(e);if(Dy(r,v2),r.schema!==to)throw new Error(`Expected Native transition schema ${to}`);let i=By(r,t,!0),n=ro(r.previousState),a=ro(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Fy(n,a,i,u_(n,a,i.eventData),!0),qy(n,a,i,!0),{schema:to,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function Ly(e,t){let r=cp(e);if(Dy(r,l_),r.schema!==Xi)throw new Error(`Expected Native transition schema ${Xi}`);if(sp(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Xi} minimum_runtime_version must be 2`);let n=sp(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=By(r,t,!0),o=Ri(r.previousState),s=Ri(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Fy(o,s,a,u_(o,s,a.eventData),!0),qy(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Xi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function R2(e,t){let r=cp(e);if(r.schema===Un)return{status:"current",journal:My(r,t)};if(r.schema===to)return{status:"migration-required",journal:E2(r,t)};if(r.schema===Xi)return{status:"migration-required",journal:Ly(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function Vy(e,t){let r=Mt(e,t),i=F(e,r);await j(i,r);try{let n=await Ie({root:i,file:r,maxBytes:w2,label:`Native transition journal ${t}`});return R2(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bn(e,t){let r=await Vy(e,t);if(!r)return null;if(r.status==="migration-required")throw new $u(t);return r.journal}function a_(e,t){if(qi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(qi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function o_(e,t){if(qi(e,t.nextState))return"next";if(qi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function P2(e){let{journal:t}=e;return d_({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function d_(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function s_(e,t){let r=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),i=r.filter(({event:a})=>a.type==="run_started"),n=r.filter(({event:a})=>a.type==="state_transitioned");if(r.length!==i.length+n.length||i.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(i.length!==1||i[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...i,...n]){let o=P2({sequence:a.index+1,journal:t,type:a.event.type});if(!qi(d_(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:i[0]?.event??null,transitioned:n[0]?.event??null}}async function oc(e,t,r){if(await js(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await ch(e,t);let i=await bn(e,t);if(!i)return null;let n=V(e,t),a=s_(await Zt(n,i.nextRun.trajectoryRef),i),[o,s]=await Promise.all([pt(n),De(e,t)]),c=a_(o,i),l=o_(s,i);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${i.change}; recovery journal was preserved`);if(c==="previous"&&(await co(n,i.nextRun),await r?.afterRunStateWritten?.(i)),!qi(await pt(n),i.nextRun))throw new Error(`Native transition Run content changed while continuing ${i.change}; recovery journal was preserved`);if(l==="previous"){let m=await Fl(e,i.nextState,i.previousState.revision);if(!qi(m,i.nextState))throw new Error(`Native transition change write diverged for ${i.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(i)}if(!qi(await De(e,t),i.nextState))throw new Error(`Native transition change content changed while continuing ${i.change}; recovery journal was preserved`);let u=await bn(e,t);if(!u||!qi(u,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was preserved`);let d=s_(await Zt(n,i.nextRun.trajectoryRef),i);i.previousRun===null&&(d.started||await Sa({changeDir:n,run:i.nextRun,type:"run_started",data:{runtime:"comet-native",phase:i.previousState.phase,transitionId:i.id},now:new Date(i.createdAt)}));let f=d.transitioned;f||(f=await Sa({changeDir:n,run:i.nextRun,type:"state_transitioned",data:{...i.eventData,transitionId:i.id},now:new Date(i.createdAt)})),await Oo({changeDir:n,run:i.nextRun,trajectoryOffset:f.sequence,evidenceHash:i.evidenceHash,now:new Date(i.createdAt)});let[p,v]=await Promise.all([pt(n),De(e,t)]);a_(p,{...i,previousRun:i.nextRun}),o_(v,{...i,previousState:i.nextState});let h=await bn(e,t);if(!h||!qi(h,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was not removed`);return await p2.rm(Mt(e,t),{force:!0}),i.nextState}async function f_(e,t,r){return $(e,`continue transition ${t}`,()=>Fi(e,t,`continue transition ${t}`,()=>oc(e,t,r)))}pl();Jt();Ee();Jt();pl();ct();import h_ from"node:path";var C2="comet.native.contract.v1",x2="comet.native.acceptance-set.v1",p_=/^[a-f0-9]{64}$/u,Ou={maxAcceptanceCriteria:hl.maxCriteria};function m_(e,t){let r=h_.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||h_.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function v_(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
278
|
-
`))}function A2(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(p_))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(p_))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=m_(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:v_(e.markdown)},markdown:e.markdown}}function _2(e,t){return g_(e.id,t.id)}function g_(e,t){return e<t?-1:e>t?1:0}function w_(e){let t=m_(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(A2).sort((d,f)=>g_(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Pf(e.briefMarkdown,t,Ou.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Cf(f,d.source,Ou.maxAcceptanceCriteria-a.length)),a.push(...RE(f,d.source,Ou.maxAcceptanceCriteria-a.length)));if(a.sort(_2),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ou.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ou.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:v_(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=D(x2,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(C2,u)}}var mi={maxSpecs:64,maxFileBytes:bc,maxTotalBytes:4*1024*1024};async function kn(e){if(e.specChanges.length>mi.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:mi.maxFileBytes}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:mi.maxFileBytes});if(r+=a.size,r>mi.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:w_({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}zr();na();on();au();import{execFile as W2}from"node:child_process";mh();tw();Ee();import{promisify as z2}from"node:util";Ee();import{promises as D2}from"fs";$e();Ee();qr();Q();Yt();Nc();rn();import sc from"path";var Ra={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},cc=/^[a-f0-9]{64}$/u;function lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function up(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Ea(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function y_(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wy(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function I2(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||sc.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=sc.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function zy(e,t){return sc.join(V(e,t),"checkpoints","progress.json")}function Pa(e,t){return sc.join(V(e,t),"checkpoint-journal.json")}function Jy(e,t,r){if(!cc.test(r))throw new Error("Native checkpoint manifest hash is invalid");return sc.join(V(e,t),"checkpoints","manifests",`${r}.json`)}function T2(e){if(!cc.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Gy(e,t,r){let i=await Ie({root:e,file:t,maxBytes:Ra.maxDocumentBytes,label:r});return JSON.parse(i.bytes.toString("utf8"))}function j2(e,t){let r=lp(e,`checkpoint manifest artifact ${t}`);up(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=I2(Ea(r.path,`checkpoint artifact ${t} path`,4096)),n=yi(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!cc.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Wy(r.size,`checkpoint artifact ${t} size`)}}function dp(e,t){let r=lp(e,"Native checkpoint manifest");if(up(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Ra.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(j2),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Wy(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Ra.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Uy(e){return G(JSON.stringify(dp(e,e.change)))}function Ky(e,t){let r=lp(e,"Native progress checkpoint");if(up(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=y_(r.previousRevision,"Native checkpoint previousRevision"),a=y_(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ea(r.manifestHash,"Native checkpoint manifestHash",64);if(!cc.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=T2(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ea(r.inputHash,"Native checkpoint inputHash",64);if(!cc.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ea(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Wy(r.artifactCount,"Native checkpoint artifactCount");if(u>Ra.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ea(r.summary,"Native checkpoint summary"),f=Ea(r.nextAction,"Native checkpoint nextAction");if(mt(d)!==d||mt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ea(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function $2(e,t){let r=lp(e,"Native checkpoint journal");if(up(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=cr(r.previousState),n=cr(r.nextState),a=Ky(r.checkpoint,t),o=dp(r.manifest,t),s=Ea(r.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!cc.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Uy(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function O2(e,t,r){let i=sc.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=zp(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Ie({root:e.projectRoot,file:i,maxBytes:Ra.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function H2(e,t){let r=zy(e,t),i=F(e,r);await j(i,r);try{return Ky(await Gy(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Yy(e,t,r){let i=Jy(e,t,r),n=F(e,i);await j(n,i);let a=await Gy(n,i,"Native checkpoint manifest"),o=dp(a,t);if(Xy(e,o),Uy(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Ca(e,t){let r=Pa(e,t),i=F(e,r);await j(i,r);try{let n=$2(await Gy(i,r,"Native checkpoint journal"),t);return Xy(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function N_(e,t,r,i){let n=dp(r,t);Xy(e,n);let a=Uy(n),o=Jy(e,t,a),s=F(e,o);await j(s,o);try{let c=await Yy(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await fe(o,n,{containedRoot:s,beforeCommit:i?.beforeCommit}),a}function Xy(e,t){for(let r of t.artifacts){let i=zp(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function b_(e,t){let r=Ky(t,t.change),i=await Yy(e,r.change,r.manifestHash),n=G(JSON.stringify({summary:r.summary,nextAction:r.nextAction,artifacts:i.artifacts}));if(r.inputHash!==n||r.artifactCount!==i.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=zy(e,t.change),o=F(e,a);await j(o,a),await fe(a,r,{containedRoot:o})}async function k_(e){let t;try{t=await H2(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:zy(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await Yy(e.paths,e.name,t.manifestHash);let a=G(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await O2(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Jy(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}it();async function Qy(e,t,r){let i=await Ca(e,t);if(!i)return null;if(await N_(e,i.change,i.manifest)!==i.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Fl(e,i.nextState,i.previousState.revision,{allowPendingCheckpointRecovery:!0}),await r?.afterStateWritten?.(i),await b_(e,i.checkpoint),await r?.afterProgressWritten?.(i),await D2.rm(Pa(e,t),{force:!0}),i}async function S_(e,t,r){return $(e,`continue checkpoint ${t}`,()=>Fi(e,t,`continue checkpoint ${t}`,async()=>(await oc(e,t),Qy(e,t,r))))}async function Hu(e,t){await oc(e,t),await Qy(e,t)}$e();Ws();Q();Ir();import{constants as Zy,promises as Jr}from"node:fs";import lc from"node:path";var B2=/^[a-f0-9]{64}$/u,q2=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ho=512*1024;function F2(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function fp(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function M2(e,t){let r=lc.resolve(e),i=lc.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...lc.relative(r,i).split(lc.sep).filter(Boolean)]){o&&(a=lc.join(a,o));let s=await Jr.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Jr.realpath(a);if(n.length>0&&!q(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function E_(e){for(let t of e){let r=await Jr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!F2(t,r)||await Jr.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function R_(e){if(!B2.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function L2(e){let t=q2.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function P_(e,t,r){return Jn(V(e,t),R_(r))}async function V2(e,t,r){let i=await M2(r,lc.dirname(e)),n=await Jr.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ho)throw new Error(`Native check receipt exceeds ${Ho} bytes`);let[a,o]=await Promise.all([Jr.realpath(t),Jr.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Zy.O_RDONLY|Zy.O_NOFOLLOW|Zy.O_NONBLOCK,c=await Jr.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Jr.lstat(e),Jr.realpath(e)]);if(await E_(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!fp(n,l)||!fp(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let w=Ho+1-p,S=await c.read(v,0,Math.min(v.length,w),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>Ho)throw new Error(`Native check receipt exceeds ${Ho} bytes`);f.push(Buffer.from(v.subarray(0,S.bytesRead)))}let[h,m,g]=await Promise.all([c.stat(),Jr.lstat(e),Jr.realpath(e)]);if(await E_(i),!m.isFile()||m.isSymbolicLink()||g!==o||!q(a,g)||!fp(l,h)||!fp(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function hp(e,t,r){let i=L2(r),n=V(e,t),a=P_(e,t,i),o=F(e,a);await j(o,a);let s=ln(await V2(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}async function C_(e){let t=ln(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let r=R_(t.receiptHash),i=P_(e.paths,e.name,t.receiptHash);if(Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
279
|
-
`,"utf8")>Ho)throw new Error(`Native check receipt exceeds ${Ho} bytes`);let a=F(e.paths,i);await j(a,i);try{let s=await hp(e.paths,e.name,r);if(JSON.stringify(s)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return r}catch(s){if(s.code!=="ENOENT")throw s}await fe(i,t,{containedRoot:a});let o=await hp(e.paths,e.name,r);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return r}zr();it();rn();var Du=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};na();Js();on();var fee=64*1024;var hee=3600*1e3;var pee=z2(W2);async function x_(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[r,i]=await Promise.all([dn(e,t.name,t.implementation_scope),kn({changeDir:se(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(r.scope.contractHash!==i.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let n=t.run_id?`run:${t.run_id}`:`scope:${r.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:i.contract.contractHash,scopeHash:r.scope.scopeHash,snapshotHash:r.scope.currentProjectionHash,artifactHash:Ih(r.scope.declaredArtifacts)},acceptanceIds:i.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${n}`,implementationExecutionId:n,scope:r}}var J2=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function eN(e,t){let r=[];for(let i of J2){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}function G2(e,t){return eN(e,t).ok}async function A_(e){let t=await x_(e.paths,e.state),r=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),i=e.checkReceipt.status==="passed"?"passed":r?"blocked":"failed",n=PC({kind:"static-inspection",role:"required-check",status:i,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:bo({baseline:t.scope.baseline,current:t.scope.current,declaredArtifacts:t.scope.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0).map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:i==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await Cw({paths:e.paths,name:e.state.name,receipt:n});return{receipt:n,ref:a}}function U2(e){let{receipt:t,checkReceipt:r,context:i}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!G2(t,i.bindings)||r.status!=="passed"||r.stale)return!1;let n=bo({baseline:i.scope.baseline,current:i.scope.current,declaredArtifacts:i.scope.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return r.change===i.bindings.change&&r.sourceRevision===i.bindings.sourceRevision&&r.contract.expectedHash===i.bindings.contractHash&&r.contract.beforeHash===i.bindings.contractHash&&r.contract.afterHash===i.bindings.contractHash&&r.implementation.scopeHash===i.bindings.scopeHash&&r.implementation.expectedSnapshotHash===i.bindings.snapshotHash&&r.implementation.beforeSnapshotHash===i.bindings.snapshotHash&&r.implementation.afterSnapshotHash===i.bindings.snapshotHash&&r.counts.filesSelected===n.length&&r.counts.filesScanned+r.counts.binaryFilesSkipped===n.length&&r.counts.bytesScanned===a&&r.counts.issueCount===0&&r.counts.recordedIssueCount===0&&r.issues.length===0&&!r.issuesTruncated}async function __(e){let t=await xw(e.paths,e.state.name);if(t.length===0)return null;let r=[];for(let a of t)try{let o=await Eo(e.paths,e.state.name,a);o.kind==="static-inspection"&&o.role==="required-check"&&o.status==="passed"&&r.push({ref:a,receipt:o})}catch{}if(r.length===0)return null;let i;try{if(i=await x_(e.paths,e.state),!(await Q2({paths:e.paths,context:i})).matched)return null}catch{return null}let n=null;for(let{ref:a,receipt:o}of r)try{let s=await tN({paths:e.paths,state:e.state,receipt:o});if(s===null||!U2({receipt:o,checkReceipt:s,context:i}))continue;let c={receipt:o,ref:a,checkReceipt:s,checkReceiptRef:o.evidence.checkReceiptRef};(n===null||c.receipt.issuedAt>n.receipt.issuedAt||c.receipt.issuedAt===n.receipt.issuedAt&&c.ref>n.ref)&&(n=c)}catch{}return n}function K2(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}var Y2=20;function X2(e,t){let r=[],i=0,n=0,a=0;for(;n<e.entries.length||a<t.entries.length;){let o=e.entries[n],s=t.entries[a],c=o===void 0?1:s===void 0||o.path<s.path?-1:o.path>s.path?1:0,l=c<=0?o:void 0,u=c>=0?s:void 0;if(c<=0&&(n+=1),c>=0&&(a+=1),l&&u&&l.hash===u.hash&&l.size===u.size)continue;let d=l?.path??u?.path;d&&(i+=1,r.length<Y2&&r.push({path:d,kind:l?u?"modified":"removed":"added"}))}return{changedPaths:r,changedPathCount:i,changedPathsTruncated:r.length!==i}}async function Q2(e){let t=K2(e.context.scope.baseline),r=await Es(e.paths,t,{origin:"explicit",now:e.now}),i=Fs({baseline:t,current:r,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths,externalDrift:e.context.scope.authority.externalDrift}),n=X2(e.context.scope.current,i.current);return{expectedScopeHash:e.context.bindings.scopeHash,actualScopeHash:i.scope.scopeHash,expectedSnapshotHash:e.context.bindings.snapshotHash,actualSnapshotHash:i.scope.currentProjectionHash,matched:i.scope.currentProjectionHash===e.context.bindings.snapshotHash&&i.scope.scopeHash===e.context.bindings.scopeHash,...n}}async function tN(e){if(e.receipt.kind!=="static-inspection")return null;let t=await hp(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}Js();var xa=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function Z2(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function ez(e){let t=Z2(e.bundle.baseline),r=await Es(e.paths,t,{origin:"explicit",now:e.now});return Fs({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function T_(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await dn(e.paths,e.state.name,e.state.implementation_scope),r=await kn({changeDir:se(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await ez({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function j_(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await T_(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function tz(e){let t=await re({root:se(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:CE(t.text)}}function rz(e){let{receipt:t,implementationScope:r}=e,i=[],n=bo({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function iz(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Ih(e.implementationScope.scope.declaredArtifacts)}}async function I_(e){let t=await Eo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=eN(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new xa([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await tN({paths:e.paths,state:e.state,receipt:t});if(n){let a=rz({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function nz(e){let t=iz({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await I_({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof xa)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await I_({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof xa)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new xa(r)}function rN(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function pp(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:rN(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([T_(e),Ro(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:rN(e.state.verification_result,"stale"),envelope:null};let i=await tz({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await nz({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:rN(e.state.verification_result,"invalid"),envelope:null}}}Lr();function oz(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function O_(e){try{return await az.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function sz(e,t){try{return(await re({root:e,ref:t})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function cz(e,t,r){let i=ca(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=$_.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await sz(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await re({root:se(e,t),ref:r.source})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function lz(e,t){return O_(Mt(e,t))}async function mp(e){let t=e.now??new Date,r=await De(e.paths,e.name),i=await Dt(e.paths,e.name),n=await X(e.paths.projectRoot),a=oz(r.name,t),o=$_.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(r.spec_changes.map(v=>cz(e.paths,r.name,v))),pp({paths:e.paths,state:r,now:t}),ip(e.paths,r.name),js(e.paths,r.name),$s(e.paths,r.name),lz(e.paths,r.name),O_(o)]);return HA({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}qr();Yt();import{promises as iN}from"node:fs";import Sn from"node:path";var uz="comet.native.archive-tree.v1",dz={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function B_(e){let t={...dz,...e};for(let[r,i]of Object.entries(t))if(!Number.isSafeInteger(i)||i<=0)throw new Error(`Native Archive content limit ${r} must be a positive safe integer`);return t}function H_(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,r)=>t.name.localeCompare(r.name)))}function D_(e,t,r,i){if(r.entryCount+=1,r.entryCount>i.maxEntries)throw new Error(`Native Archive content exceeds ${i.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>i.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${i.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(r.manifestBytes+=n+(e.length===0?0:1),r.manifestBytes+2>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);e.push(t)}async function q_(e,t,r,i,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await lr({root:e,directory:t,label:`Native Archive content directory ${Sn.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=H_(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Sn.join(t,u.name),f=Sn.relative(e,d).replaceAll("\\","/"),p=await iN.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){D_(r,{ref:f,kind:"directory"},i,n),await q_(e,d,r,i,n,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await Ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(i.totalBytes+=v.size,i.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);D_(r,{ref:f,kind:"file",hash:v.hash,size:v.size},i,n),await o.verify()}await o.verify();let l=await lr({root:e,directory:t,label:`Native Archive content directory ${Sn.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(H_(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Sn.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function F_(e,t={}){let r=B_(t);e=Sn.resolve(e);let i=await iN.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await q_(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},r,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);return G(`${uz}\0${o}`)}async function vi(e,t={}){let r=B_(t);e=Sn.resolve(e);let i;try{i=await iN.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(i.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(i.isFile())return{kind:"file",hash:(await Ie({root:Sn.dirname(e),file:e,maxBytes:r.maxFileBytes,label:`Native Archive transaction file ${Sn.basename(e)}`})).hash};if(i.isDirectory())return{kind:"directory",hash:await F_(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}$e();Ir();import{promises as rr}from"node:fs";import dt from"node:path";Q();Yt();oo();var aN=16*1024*1024,fz=256*1024,hz=16*1024,Bu="comet.native.archive-cas.v1";function pz(e,t){let r="runtime/",i=t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(r.length):t,o=dt.resolve(n,...a.split("/"));if(!q(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function _t(e,t){let r=pz(e,t);return j(F(e,r),r)}function Aa(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function uc(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function vr(e){let t=await vi(e.target);if(!Aa(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${uc(t)}`);return t}async function oN(e,t){let r=await Ci(e,t),i=await Ie({root:e.runtimeDir,file:r.journal,maxBytes:fz,label:`Native Archive transaction journal ${t}`}),n=Vf(JSON.parse(i.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function vp(e,t,r){let i=Vf({...t,status:r}),n=await Ci(e,i.id);return await fe(n.journal,i,{containedRoot:e.runtimeDir}),i}function gp(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function M_(e){return{...gp(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function _a(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function mz(e,t){return _a(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function _e(e){try{return await rr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Mi(e){let t=await rr.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=M_(t),i=await Ie({root:F(e.paths,e.file),file:e.file,maxBytes:aN,label:e.label}),n=await rr.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!mz(r,M_(n))||i.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:gp(n),size:i.size}}function vz(e,t,r,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${r} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${r} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${r} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${r} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${r} identity ${c} is invalid`);if(n.schema!==Bu||n.operationId!==t.id||n.role!==r||n.hash!==i)throw new Error(`Archive CAS ${t.id} ${r} record is not transaction-bound`);return{schema:Bu,operationId:t.id,role:r,hash:i,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Li(e,t,r,i){let n=await Ci(e,t.id),a=dt.join(n.backups,".cas"),o=`.${dt.basename(i)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:a,originalRecord:dt.join(a,`${r.id}.original.json`),postRecord:dt.join(a,`${r.id}.post.json`),candidate:dt.join(a,`${r.id}.candidate`),originalQuarantine:dt.join(dt.dirname(i),`${o}.original`),rollbackQuarantine:dt.join(dt.dirname(i),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>j(F(e,c),c))),s}async function Gr(e){if(!await _e(e.file))return null;let t=await Ie({root:e.paths.runtimeDir,file:e.file,maxBytes:hz,label:`Archive CAS ${e.operation.id} ${e.role} record`});return vz(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function wp(e){let t=await Gr(e);if(t){if(!_a(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Pi({root:e.paths.runtimeDir,directory:dt.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Bu,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await fe(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let i=await Gr(e);if(!i||!_a(i.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return i}async function ot(e){let t=await Mi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!_a(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function gz(e){let t=await Mi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await wp({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await ot({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function wz(e){if(!await _e(e.quarantine)||await _e(e.target))return;let t=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rr.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[r,i]=await Promise.all([rr.lstat(e.quarantine),rr.lstat(e.target)]);if(!_a(gp(r),gp(i)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rr.unlink(e.quarantine),await t.verify()}async function z_(e){if(await _e(e.quarantine)){await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await ot({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await ot({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rr.rename(e.target,e.quarantine),await t.verify(),await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await wz(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:r})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Do(e){if(!await _e(e.file))return;await ot(e);let t=await br({root:F(e.paths,e.file),directory:dt.dirname(e.file),label:e.label});await t.verify(),await ot(e),await rr.unlink(e.file),await t.verify()}async function L_(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let i=await _t(e,t.target),n=await _t(e,t.backup),a=await vi(n);if(a!==null){if(!Aa(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await vr({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Zn({sourceRoot:F(e,i),source:i,targetRoot:F(e,n),target:n,maxBytes:aN,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await vr({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function J_(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let r=await Li(e.paths,e.journal,e.operation,e.target),i=await Gr({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await _e(r.originalQuarantine)){if(!i)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await ot({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:i,label:`Archive apply quarantine ${e.operation.target}`}),await L_(e.paths,e.operation,e.hooks),{record:i,quarantine:r.originalQuarantine}}if(!await _e(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return i??=await gz({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await ot({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive apply target ${e.operation.target}`}),await L_(e.paths,e.operation,e.hooks),await z_({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:r.originalQuarantine,record:i,hooks:e.hooks}),{record:i,quarantine:r.originalQuarantine}}async function V_(e){let t=await Li(e.paths,e.journal,e.operation,e.target);return await _e(t.candidate)?(await Mi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Pi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Zn({sourceRoot:F(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:aN,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function yz(e){let t=e.operation.stagedHash,r=await Li(e.paths,e.journal,e.operation,e.target),i=await Gr({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(i&&await _e(e.target))return await ot({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive write target ${e.operation.target}`}),await _e(r.candidate)&&await Do({paths:e.paths,file:r.candidate,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i;if(await _e(e.target)){let c=await V_(e),l=await Mi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Mi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!_a(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return i=await wp({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Do({paths:e.paths,file:c,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}let n=await V_(e),a=await Mi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Pi({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await ot({paths:e.paths,file:n,operation:e.operation,record:{schema:Bu,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rr.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Mi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!_a(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return i=await wp({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Do({paths:e.paths,file:n,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}async function Nz(e,t,r,i){let n=await _t(e,r.target),a=await _t(e,r.staged);if(await vr({target:a,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let o=await Li(e,t,r,n);(!await Gr({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await _e(n))&&await J_({paths:e,journal:t,operation:r,target:n,hooks:i})}else{let o=await vi(n);if(o!==null&&!Aa(o,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${uc(o)}`)}await yz({paths:e,journal:t,operation:r,staged:a,target:n,hooks:i}),await vr({target:n,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function bz(e,t,r,i){let n=await _t(e,r.target);await J_({paths:e,journal:t,operation:r,target:n,hooks:i}),await vr({target:n,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function kz(e,t){let r=await _t(e,t.source),i=await _t(e,t.target),[n,a]=await Promise.all([vi(r),vi(i)]);if(!(n===null&&Aa(a,t.expectedSourceHash,"directory"))){if(!Aa(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${uc(n)}, target=${uc(a)}`);await rr.mkdir(dt.dirname(i),{recursive:!0}),await rr.rename(r,i),await vr({target:i,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function Sz(e,t,r,i){return r.type==="write"?Nz(e,t,r,i):r.type==="remove"?bz(e,t,r,i):kz(e,r)}function Ez(e){let t=0,r=!1,i=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){r=!0;continue}if(!r)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);i.push(a.id),t+=1,r=!1}return i}async function Rz(e,t,r,i){let n=await _t(e,r.target);if(r.type==="write"){let a=await _t(e,r.staged);await vr({target:a,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let o=await Li(e,t,r,n),s=await Gr({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!s)throw new Error(`Completed Archive target ${r.target} has no CAS identity`);if(await ot({paths:e,file:n,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await vr({target:await _t(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await Gr({paths:e,file:o.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${r.target} has no original CAS identity`);if(await _e(o.originalQuarantine))await ot({paths:e,file:o.originalQuarantine,operation:r,record:c,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`)}return}if(r.type==="remove"){await vr({target:n,expectedHash:null,label:`Completed Archive target ${r.target}`}),await vr({target:await _t(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let a=await Li(e,t,r,n),o=await Gr({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${r.target} has no original CAS identity`);if(await _e(a.originalQuarantine))await ot({paths:e,file:a.originalQuarantine,operation:r,record:o,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`);return}i||(await vr({target:await _t(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await vr({target:n,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function G_(e,t,r){let i=t.status==="prepared"?await vp(e,t,"applying"):t;if(i.status!=="applying")throw new Error(`Native Archive transaction ${i.id} cannot apply from ${i.status}`);let n=await ta(e,i.id),a=Ez({journal:i,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of i.operations.slice(0,a.length))await Rz(e,i,l,s);let c=o.size;for(let l of i.operations)o.has(l.id)||(l.id==="archive-change"&&await r?.beforeArchiveChangeMove?.(l),await Dr(e,i.id,"operation-started",l.id),await Sz(e,i,l,r),await Dr(e,i.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return i=await oN(e,i.id),i}async function Pz(e){try{return await ot(e),!0}catch{return!1}}async function Cz(e){await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rr.link(e.quarantine,e.target)}catch(r){throw r.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:r}):r}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await ot({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function nN(e){if(e.operation.type!=="write")return;let t=await Li(e.paths,e.journal,e.operation,e.target);if(!await _e(t.candidate))return;let r=await Mi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Do({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Bu,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function xz(e,t,r,i){let n=await _t(e,r.target),a=await Li(e,t,r,n),o=r.expectedTargetHash,s=o===null?null:await Gr({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:o}),c=r.type==="write"?await Gr({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await _e(a.candidate)&&await _e(n)){let l=await Mi({paths:e,file:a.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await Mi({paths:e,file:n,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});_a(l.identity,u.identity)&&(c=await wp({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await _e(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await ot({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await _e(n)&&!(s!==null&&await Pz({paths:e,file:n,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await vi(n);if(Aa(u,o)){await nN({paths:e,journal:t,operation:r,target:n});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await z_({paths:e,operation:r,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:i})}if(o===null){if(await _e(n))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await _e(n)){if(!s||!await _e(a.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await Cz({paths:e,operation:r,target:n,quarantine:a.originalQuarantine,record:s,hooks:i})}s&&await _e(a.originalQuarantine)&&await Do({paths:e,file:a.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await _e(a.rollbackQuarantine)&&await Do({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await nN({paths:e,journal:t,operation:r,target:n}),await vr({target:n,expectedHash:o,label:`Archive rollback target ${r.target}`})}async function Az(e,t){let r=await _t(e,t.source),i=await _t(e,t.target),[n,a]=await Promise.all([vi(r),vi(i)]);if(!(Aa(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Aa(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${uc(n)}, target=${uc(a)}`);await rr.mkdir(dt.dirname(r),{recursive:!0}),await rr.rename(i,r)}}async function U_(e,t,r){let i=await ta(e,t.id);if(i.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await vp(e,t,"rolling-back");await Dr(e,n.id,"rollback-started");let a=new Set(i.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await Az(e,o):await xz(e,n,o,r));return await Dr(e,n.id,"rollback-completed"),n=await vp(e,n,"rolled-back"),n}async function W_(e,t,r){let i=await _t(e,r.target);if(r.type==="write"){let n=await Li(e,t,r,i),a=await Gr({paths:e,file:n.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!a)throw new Error(`Archive commit target ${r.target} has no CAS identity`);await ot({paths:e,file:i,operation:r,record:a,label:`Archive commit target ${r.target}`});return}await vr({target:i,expectedHash:null,label:`Archive commit target ${r.target}`})}async function _z(e,t){for(let r of t.operations){if(r.type==="move")continue;let i=await _t(e,r.target),n=await Li(e,t,r,i);if(await _e(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await W_(e,t,r),r.expectedTargetHash!==null){let a=await Gr({paths:e,file:n.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${r.target} has no original CAS identity`);await _e(n.originalQuarantine)&&await Do({paths:e,file:n.originalQuarantine,operation:r,record:a,label:`Archive commit original quarantine ${r.target}`})}await nN({paths:e,journal:t,operation:r,target:i})}for(let r of t.operations)r.type!=="move"&&await W_(e,t,r)}async function yp(e,t,r){return r==="commit"&&await _z(e,t),await Dr(e,t.id,r),r==="commit"?vp(e,t,"committed"):t}Ee();$e();Va();Ee();zr();var ote=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});qr();Qa();it();Q();Yt();oo();var Ote=16*1024*1024,Np=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},qu=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function Y_(e,t){let r=t.operations.find(i=>i.id==="archive-change");if(!r||r.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return dc.resolve(e.nativeRoot,...r.target.split("/"))}async function X_(e,t,r){let i=await ta(e,t.id);if(i.some(m=>m.type==="archive-finalized"))return;let n=i.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(w=>w.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await vi(Y_(e,t));if(g?.kind!=="directory"||g.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Y_(e,t),o=dc.join(a,lt),s=await wP(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=V(e,s.name),l=await pt(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=TA(Bi,l,new Set,$y,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=jA(Bi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},$y,void 0)}let d=G(`archive:${t.id}:${s.name}`),f=await Zt(c,u.trajectoryRef),p=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=p.find(m=>m.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!Iz(v.data,h)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await yp(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await ws(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await gP(o,m)}v||(v=await Sa({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Oo({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await co(c,u),await Cu(e,s.name),t.schema==="comet.native.transaction.v2"?await yp(e,t,"archive-finalized"):await ws(e,t,"archive-finalized")}async function sN(e,t){let r=Oe(e,t);try{let i=await K_.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${r}`);return await j(e.runtimeDir,r),await K_.rm(r,{recursive:!0,force:!0}),null}catch(i){return i.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${i.message}`}}async function Tz(e,t,r){if(t.schema==="comet.native.transaction.v2"){if(!(await ta(e,t.id)).some(c=>c.type==="operation-started")){let c=await mp({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new qu(c,"Native Archive facts changed before the first transaction operation")}let o=await G_(e,t,{...r,beforeArchiveChangeMove:async c=>{await r?.beforeArchiveChangeMove?.(c);let l=await De(e,t.change),u=await pp({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await X_(e,o,r);let s=await yp(e,o,"commit");return{journal:s,runtimeCleanupWarning:await sN(e,s.change)}}let i=await eR(e,t);await X_(e,i,r);let n=await ws(e,i,"commit");return{journal:n,runtimeCleanupWarning:n.change?await sN(e,n.change):null}}function jz(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(dc.resolve(t.projectRoot)!==dc.resolve(e.projectRoot)||dc.resolve(t.nativeRoot)!==dc.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Q_(e){return $(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await Ui(e.paths,"archive",`recover archive ${e.transactionId}`);try{let r=await ur(e.paths,e.transactionId),i=r.schema==="comet.native.transaction.v2"?await oN(e.paths,e.transactionId):r;return jz(e.paths,i),i.status==="committed"?(i.change&&await sN(e.paths,i.change),i):i.status==="rolled-back"?i:e.strategy==="continue"?(await Tz(e.paths,i)).journal:i.schema==="comet.native.transaction.v2"?U_(e.paths,i):zf(e.paths,i)}finally{await Ki(t)}},{allowedTransactionId:e.transactionId})}Ee();Q();tt();function ae(e,t,r){return e==="zh-CN"?r:t}var cN={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Z_(e,t){return typeof e=="string"&&cN[e]?ae(t,cN[e].en,cN[e].zh):typeof e=="string"?e:""}function lN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function $z(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function eI(e,t){let r=[];e.failed>0&&r.push(ae(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(ae(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(ae(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=ae(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function tI(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function uN(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function Oz(e,t,r){return e==="done"?ae(r,"complete","已完成"):e==="await-user"?ae(r,"waiting for a user decision","等待用户决定"):e==="blocked"?ae(r,"paused: needs attention","已暂停,需要处理"):t?ae(r,"waiting for a user decision","等待用户决定"):ae(r,"ready to continue","可继续推进")}function Hz(e,t,r){let i=uN(e),n=[];r&&n.push(r);let a=ae(i,`Change ${e.change}`,`需求 ${e.change}`),o=Z_(e.phase,i),s=Oz(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(eI(t,i));let c=e.userCommunication,l=rI(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function rI(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:ae(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:ae(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:ae(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Dz(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Bz(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Z_(e.phase,t),n=e.status==="await-user"?ae(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?ae(t,"paused","已暂停"):e.status==="done"?ae(t,"complete","已完成"):ae(t,"in progress","进行中"),a=lN(e.acceptance)?`${ae(t,", ",",")}${eI(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function qz(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Fz(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function Mz(e){if(e.healthy){let i=e.repaired?ae("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):ae("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=Lz(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:ae("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:ae("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function Lz(e){return tI(e)?rI(e,uN(e)):void 0}function iI(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Fz(t))return Mz(t);if(Dz(t)){let i=qz(t.items);return{summary:[t.total===t.items.length?ae(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):ae(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>Bz(a,i))].join(`
|
|
280
|
-
`)}}let r=t.continuation;if(tI(r))return Hz(r,Vz(t),Wz(t,uN(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:ae(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function Vz(e){if(lN(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(lN(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return $z(r.acceptance)}return null}function Wz(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return ae(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?ae(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function nI(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:ae("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:ae("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:ae("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:ae("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:ae("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:ae("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:ae("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:ae("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:ae("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Eh();var aI=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],fN=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","
|
|
281
|
-
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"
|
|
276
|
+
`)}import{promises as K_}from"fs";import dc from"path";import{isDeepStrictEqual as Iz}from"util";import{createHash as vW}from"crypto";function AA(e,t,r,i){return t.iteration>=r.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${r.maxIterations}`}:e.type==="invoke_skill"&&!r.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!r.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!r.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&r.confirmationRequiredFor.includes(e.ref)&&!i.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>r.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function _A(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))_A(e[t]);return Object.freeze(e)}function ka(e){return _A(structuredClone(e))}function Ey(e,t,r,i){return e.resolveStep({pkg:ka(t),state:ka(r),context:ka(i)})}function IA(e,t,r,i,n,a){return e.resolveNext({pkg:ka(t),state:ka(r),step:ka(i),outcome:ka(n),context:ka(a)})}function gW(e,t,r){return vW("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function Ry(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function TA(e,t,r,i,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=Ey(i,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=Ry(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:gW(s.runId,s.iteration,o.id),stepId:o.id};return wW(e,s,c,r)}function wW(e,t,r,i){let n=AA(r,t,e.guardrails,i);return n.allowed?{state:{...t,pending:r.id,status:"waiting"},action:r}:{state:t,action:null,reason:n.reason}}function jA(e,t,r,i,n){if(!t.pending||t.pending!==r.actionId)throw new Error(`Outcome does not match pending action: ${r.actionId}`);let a=t.orchestration==="deterministic"?Ey(i,e,t,n):void 0,o=a?Ry(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(r.status==="failed"){let c={...t.retries,[r.actionId]:(t.retries[r.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?IA(i,e,t,o,r,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Ry(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}en();import{promises as az}from"node:fs";import $_ from"node:path";ct();import $A from"node:path";var yW="comet.native.archive-preflight.v1",NW="comet.native.archive-preflight.v1",bW="comet.native.archive-operation.v1",kW=/^[a-f0-9]{64}$/u,OA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SW=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function rp(e,t){return e<t?-1:e>t?1:0}function EW(e,t){if(typeof e!="string"||!kW.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Nn(e,t){return e===null?null:EW(e,t)}function RW(e,t){let r=$A.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||$A.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function PW(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function CW(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function xW(e,t){if(!OA.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let r=Nn(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=Nn(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Nn(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:r,actualBaseHash:i,proposedHash:n}}function AW(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:Nn(e.contractHash,"Native archive contract hash"),acceptanceHash:Nn(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Nn(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Nn(e.reportHash,"Native archive report hash"),envelopeHash:Nn(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Nn(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(r=>r===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function _W(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!SW.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(rp);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function IW(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(rp)}function HA(e){if(!OA.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(xW).sort((l,u)=>rp(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let r=t.map(l=>({...l,operationHash:B(bW,l)})),i=AW(e.evidence),n=CW(e.workspace),a=[...new Set([..._W(e.findingCodes??[]),...IW({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(rp),o=PW(e.revision),s=RW(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:r,evidence:i,workspace:n,findingCodes:a};return{schema:yW,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:B(NW,c)}}Jt();Ee();ct();import{createHash as TW}from"node:crypto";import DA from"node:path";var jW="comet.native.conflict-radar.v1",mr=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}),$W="comet.native.conflict-radar.v1",OW="comet.native.conflict-radar-signals.v1",HW=/^[a-f0-9]{64}$/u,FA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DW=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),BW=new Set(["capability","operation","baseHash"]),qW=new Set(["path","kind"]);function nc(e,t){return e<t?-1:e>t?1:0}function Py(e){return Buffer.byteLength(e,"utf8")}function Cy(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function xy(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(Py(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function FW(e,t){let r=xy(e,t,mr.maxArtifactPathBytes),i=DA.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||DA.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function MA(e,t){if(typeof e!="string"||!HW.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MW(e,t){let r=Cy(e,BW,t),i=xy(r.capability,`${t} capability`,mr.maxCapabilityBytes);if(!FA.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:MA(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function LW(e,t){let r=Cy(e,qW,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:FW(r.path,`${t} path`),kind:r.kind}}function VW(e,t){let r=Cy(e,DW,`Conflict radar change ${t}`),i=xy(r.name,`Conflict radar change ${t} name`,mr.maxNameBytes);if(!FA.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>mr.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>mr.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>MW(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>nc(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>LW(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>nc(c.path,l.path)||nc(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:MA(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function WW(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>mr.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(VW).sort((n,a)=>nc(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>mr.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>mr.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function zW(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function JW(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function GW(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function UW(e,t){let r=[],i=TW("sha256").update(`${OW}
|
|
277
|
+
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(dl(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<mr.maxSignalsPerRelationship&&r.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(zW(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=JW(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:GW(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function BA(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function KW(e,t){return BA(e.classification)-BA(t.classification)||nc(e.left,t.left)||nc(e.right,t.right)}function qA(e,t,r,i){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:jW,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function LA(e){let t=WW(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(UW(t[s],t[c]));r.sort(KW);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=B($W,{changes:t,relationships:i}),a=r.slice(0,mr.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=qA(t,r,a,n);for(;a.length>0&&Py(JSON.stringify(o))>mr.maxSerializedBytes;)a=a.slice(0,-1),o=qA(t,r,a,n);if(Py(JSON.stringify(o))>mr.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}zr();Yt();Lr();var YW=4096;async function XW(e,t=mr.maxChanges){try{let r=await lr({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function VA(e,t){let r=await Be(e,t),[i,n]=await Promise.all([r.implementation_scope?Us(e,t,r.implementation_scope):null,Dt(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ip(e,t,r={}){let n=(await XW(e,YW)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await VA(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await VA(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=LA([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}Ee();tt();Q();Ps();Oe();Ee();qr();Qa();it();Q();Yt();nn();import{promises as p2}from"fs";import m2 from"path";import{isDeepStrictEqual as op}from"util";ct();ct();var ac={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var QW=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function ZW(e,t){return e<t?-1:e>t?1:0}function e2(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!QW.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(ZW)}function Ay(e=[]){return e2(e,"Native repair failed check IDs",ac.maxFailedCheckIds,!0)}function WA(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function t2(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:WA(e.failedAcceptanceIds,t.failedAcceptanceIds)&&WA(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function _y(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(t2(i,a))break;r+=1,i=a}return r}au();sn();function np(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var zA="repairStagnation",Cr={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},i2=/^[a-f0-9]{64}$/u;var n2=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),a2=["data","runId","sequence","timestamp","type"],JA=["disposition","overrideSummaryHash","signatureHash"],o2=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],GA=12;function Ty(e,t){return e<t?-1:e>t?1:0}function UA(e,t,r){let i=Object.keys(e).sort(Ty);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function ap(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function Tu(e,t){if(typeof e!="string"||!i2.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function s2(e){if(!Array.isArray(e)||e.length>ac.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Ty)}function KA(e){if(typeof e!="string"||e.length===0||e.length>Cr.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Iy(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Cr.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Cr.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Cr.maxTextCharacters&&(!n||e.length>Cr.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Cr.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Cr.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Iy(s,t+1,r,`${i}[${c}]`));return}let a=ap(e,i),o=Object.keys(a);if(o.length>Cr.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Cr.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Cr.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Iy(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function c2(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function l2(e,t,r){let i=ap(e,`Native repair trajectory event ${t+1}`);if(UA(i,a2,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(c2(i.timestamp),typeof i.type!="string"||!n2.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(KA(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Iy(i.data,0,n,"Native trajectory event data"),ap(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function jy(e){let t=ap(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Ty),i=r.length===JA.length&&r.every((l,u)=>l===JA[u]);i||UA(t,o2,"Native repair trajectory projection");let n=Tu(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:Tu(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=Tu(t.contractHash,"Native repair trajectory contract hash"),s=s2(t.failedAcceptanceIds),c=Ay(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function u2(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function d2(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??GA;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=_y({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<ac.warningAtConsecutiveFailures?"continue":a<ac.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function f2(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??GA;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function YA(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Cr.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=KA(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=l2(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Cr.maxTotalDataNodes||c>Cr.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?Tu(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?Tu(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,zA)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(p!==null&&n!==null&&p!==n||p===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=null,n=p,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=jy(f[zA]);if(u2(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(r.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),d2(v,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");f2(v,r,i);let h=r.at(-1);if(!h||h.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:h.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(i=v,r.length>ac.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function XA(e){return YA(e).history}function QA(e){let t=YA(e).latestProjection;return t?{...t}:null}qr();var qi={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:[]},ju=G("comet-native-runtime:v3:scope-reopen"),h2=[{skillVersion:"3",skillHash:G("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:G("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:G("comet-native-runtime:v1")}];function ZA(e){return e.skillVersion===qi.definition.metadata.version&&e.skillHash===ju||h2.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var $y={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(r=>r.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};en();qr();en();async function Sa(e){let r={sequence:(await Zt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await GR(e.changeDir,e.run.trajectoryRef,r),r}async function Oo(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:G(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await UR(e.changeDir,e.run.checkpointRef,t),t}qr();function e_(e){return G(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}Il();wl();var c_=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],v2=new Set(c_),l_=new Set([...c_,"minimum_runtime_version","revision"]),g2=new Set([...l_,"operation"]),w2=512*1024,Oy=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),y2=new Set([...Oy,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),$u=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Mt(e,t){return m2.join(V(e,t),"transition.json")}function N2(e){return`transition-${e}`}async function b2(e,t,r){let i=N2(t);return Ki(e,i,r)}async function Mi(e,t,r,i){let n=await b2(e,t,r);try{return await i()}finally{await Yi(n)}}function cp(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Dy(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function sp(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Fi(e,t){return op(e,t)}function Hy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!y2.has(u)),a=[...Oy].find(u=>!Object.hasOwn(r,u)),o=Oy.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(np(r.summary,"Native transition journal event summary"),mt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(np(r.noCodeReason,"Native transition journal event no-code reason"),mt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?jy(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function k2(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Hy({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Hy(e,t)}function By(e,t,r=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let i=r?k2(e.eventData,e.evidenceHash):Hy(e.eventData,e.evidenceHash),n=oa(e.nextRun),a=e.previousRun===null?null:oa(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function t_(e,t,r=!1){if(e.skill!==qi.definition.metadata.name||(r?!ZA(e):e.skillVersion!==qi.definition.metadata.version||e.skillHash!==ju)||e.orchestration!==qi.definition.orchestration.mode||e.pendingRef!==kr.pendingRef||e.trajectoryRef!==kr.trajectoryRef||e.contextRef!==kr.contextRef||e.artifactsRef!==kr.artifactsRef||e.checkpointRef!==kr.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function r_(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function i_(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function qy(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(t_(o,"next Run",i||a!==null),i_(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(t_(a,"previous Run",!0),i_(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!op(r_(a),r_(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function S2(e,t,r){return G(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function u_(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function n_(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Fy(e,t,r,i,n=!1){let a=r.eventData,o=n_(e),s=n_(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(i==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&op(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(i==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&op(e.spec_changes,t.spec_changes),l=e_({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||r.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(i==="spec-rebase"){let c=S2(e.name,a.summary,t.spec_changes),l=G(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function My(e,t){let r=cp(e);if(Dy(r,g2),r.schema!==Un)throw new Error(`Expected Native transition schema ${Un}`);let i=sp(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Un} minimum_runtime_version must be ${3}`);let n=sp(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=By(r,t),o=cr(r.previousState),s=cr(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Fy(o,s,a,r.operation),qy(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Un,minimum_runtime_version:3,revision:n,operation:r.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function E2(e,t){let r=cp(e);if(Dy(r,v2),r.schema!==to)throw new Error(`Expected Native transition schema ${to}`);let i=By(r,t,!0),n=ro(r.previousState),a=ro(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Fy(n,a,i,u_(n,a,i.eventData),!0),qy(n,a,i,!0),{schema:to,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function Ly(e,t){let r=cp(e);if(Dy(r,l_),r.schema!==Qi)throw new Error(`Expected Native transition schema ${Qi}`);if(sp(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Qi} minimum_runtime_version must be 2`);let n=sp(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=By(r,t,!0),o=Pi(r.previousState),s=Pi(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Fy(o,s,a,u_(o,s,a.eventData),!0),qy(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Qi,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function R2(e,t){let r=cp(e);if(r.schema===Un)return{status:"current",journal:My(r,t)};if(r.schema===to)return{status:"migration-required",journal:E2(r,t)};if(r.schema===Qi)return{status:"migration-required",journal:Ly(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function Vy(e,t){let r=Mt(e,t),i=F(e,r);await j(i,r);try{let n=await Te({root:i,file:r,maxBytes:w2,label:`Native transition journal ${t}`});return R2(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function bn(e,t){let r=await Vy(e,t);if(!r)return null;if(r.status==="migration-required")throw new $u(t);return r.journal}function a_(e,t){if(Fi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Fi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function o_(e,t){if(Fi(e,t.nextState))return"next";if(Fi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function P2(e){let{journal:t}=e;return d_({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function d_(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function s_(e,t){let r=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),i=r.filter(({event:a})=>a.type==="run_started"),n=r.filter(({event:a})=>a.type==="state_transitioned");if(r.length!==i.length+n.length||i.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(i.length!==1||i[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...i,...n]){let o=P2({sequence:a.index+1,journal:t,type:a.event.type});if(!Fi(d_(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:i[0]?.event??null,transitioned:n[0]?.event??null}}async function oc(e,t,r){if(await js(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await ch(e,t);let i=await bn(e,t);if(!i)return null;let n=V(e,t),a=s_(await Zt(n,i.nextRun.trajectoryRef),i),[o,s]=await Promise.all([pt(n),Be(e,t)]),c=a_(o,i),l=o_(s,i);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${i.change}; recovery journal was preserved`);if(c==="previous"&&(await co(n,i.nextRun),await r?.afterRunStateWritten?.(i)),!Fi(await pt(n),i.nextRun))throw new Error(`Native transition Run content changed while continuing ${i.change}; recovery journal was preserved`);if(l==="previous"){let m=await Fl(e,i.nextState,i.previousState.revision);if(!Fi(m,i.nextState))throw new Error(`Native transition change write diverged for ${i.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(i)}if(!Fi(await Be(e,t),i.nextState))throw new Error(`Native transition change content changed while continuing ${i.change}; recovery journal was preserved`);let u=await bn(e,t);if(!u||!Fi(u,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was preserved`);let d=s_(await Zt(n,i.nextRun.trajectoryRef),i);i.previousRun===null&&(d.started||await Sa({changeDir:n,run:i.nextRun,type:"run_started",data:{runtime:"comet-native",phase:i.previousState.phase,transitionId:i.id},now:new Date(i.createdAt)}));let f=d.transitioned;f||(f=await Sa({changeDir:n,run:i.nextRun,type:"state_transitioned",data:{...i.eventData,transitionId:i.id},now:new Date(i.createdAt)})),await Oo({changeDir:n,run:i.nextRun,trajectoryOffset:f.sequence,evidenceHash:i.evidenceHash,now:new Date(i.createdAt)});let[p,v]=await Promise.all([pt(n),Be(e,t)]);a_(p,{...i,previousRun:i.nextRun}),o_(v,{...i,previousState:i.nextState});let h=await bn(e,t);if(!h||!Fi(h,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was not removed`);return await p2.rm(Mt(e,t),{force:!0}),i.nextState}async function f_(e,t,r){return $(e,`continue transition ${t}`,()=>Mi(e,t,`continue transition ${t}`,()=>oc(e,t,r)))}pl();Jt();Ee();Jt();pl();ct();import h_ from"node:path";var C2="comet.native.contract.v1",x2="comet.native.acceptance-set.v1",p_=/^[a-f0-9]{64}$/u,Ou={maxAcceptanceCriteria:hl.maxCriteria};function m_(e,t){let r=h_.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||h_.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function v_(e){return B("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
278
|
+
`))}function A2(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(p_))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(p_))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=m_(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:v_(e.markdown)},markdown:e.markdown}}function _2(e,t){return g_(e.id,t.id)}function g_(e,t){return e<t?-1:e>t?1:0}function w_(e){let t=m_(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(A2).sort((d,f)=>g_(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=Pf(e.briefMarkdown,t,Ou.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Cf(f,d.source,Ou.maxAcceptanceCriteria-a.length)),a.push(...RE(f,d.source,Ou.maxAcceptanceCriteria-a.length)));if(a.sort(_2),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>Ou.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${Ou.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:v_(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=B(x2,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:B(C2,u)}}var vi={maxSpecs:64,maxFileBytes:bc,maxTotalBytes:4*1024*1024};async function kn(e){if(e.specChanges.length>vi.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await re({root:e.changeDir,ref:e.briefRef,maxBytes:vi.maxFileBytes}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await re({root:e.changeDir,ref:n.source,maxBytes:vi.maxFileBytes});if(r+=a.size,r>vi.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:w_({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}zr();na();sn();au();import{execFile as W2}from"node:child_process";mh();tw();Ee();import{promisify as z2}from"node:util";Ee();import{promises as D2}from"fs";Oe();Ee();qr();Q();Yt();Nc();nn();import sc from"path";var Ra={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},cc=/^[a-f0-9]{64}$/u;function lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function up(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function Ea(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function y_(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Wy(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function I2(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||sc.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=sc.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function zy(e,t){return sc.join(V(e,t),"checkpoints","progress.json")}function Pa(e,t){return sc.join(V(e,t),"checkpoint-journal.json")}function Jy(e,t,r){if(!cc.test(r))throw new Error("Native checkpoint manifest hash is invalid");return sc.join(V(e,t),"checkpoints","manifests",`${r}.json`)}function T2(e){if(!cc.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Gy(e,t,r){let i=await Te({root:e,file:t,maxBytes:Ra.maxDocumentBytes,label:r});return JSON.parse(i.bytes.toString("utf8"))}function j2(e,t){let r=lp(e,`checkpoint manifest artifact ${t}`);up(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=I2(Ea(r.path,`checkpoint artifact ${t} path`,4096)),n=Ni(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!cc.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Wy(r.size,`checkpoint artifact ${t} size`)}}function dp(e,t){let r=lp(e,"Native checkpoint manifest");if(up(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>Ra.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(j2),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Wy(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Ra.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Uy(e){return G(JSON.stringify(dp(e,e.change)))}function Ky(e,t){let r=lp(e,"Native progress checkpoint");if(up(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=y_(r.previousRevision,"Native checkpoint previousRevision"),a=y_(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ea(r.manifestHash,"Native checkpoint manifestHash",64);if(!cc.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=T2(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ea(r.inputHash,"Native checkpoint inputHash",64);if(!cc.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ea(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Wy(r.artifactCount,"Native checkpoint artifactCount");if(u>Ra.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ea(r.summary,"Native checkpoint summary"),f=Ea(r.nextAction,"Native checkpoint nextAction");if(mt(d)!==d||mt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ea(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function $2(e,t){let r=lp(e,"Native checkpoint journal");if(up(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=cr(r.previousState),n=cr(r.nextState),a=Ky(r.checkpoint,t),o=dp(r.manifest,t),s=Ea(r.inputHash,"Native checkpoint journal inputHash",64),c=G(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!cc.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Uy(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:i,nextState:n,checkpoint:a,manifest:o}}async function O2(e,t,r){let i=sc.resolve(e.projectRoot,...t.split("/"));if(!q(e.projectRoot,i)||q(e.nativeRoot,i)||q(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=zp(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Te({root:e.projectRoot,file:i,maxBytes:Ra.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function H2(e,t){let r=zy(e,t),i=F(e,r);await j(i,r);try{return Ky(await Gy(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Yy(e,t,r){let i=Jy(e,t,r),n=F(e,i);await j(n,i);let a=await Gy(n,i,"Native checkpoint manifest"),o=dp(a,t);if(Xy(e,o),Uy(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Ca(e,t){let r=Pa(e,t),i=F(e,r);await j(i,r);try{let n=$2(await Gy(i,r,"Native checkpoint journal"),t);return Xy(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function N_(e,t,r,i){let n=dp(r,t);Xy(e,n);let a=Uy(n),o=Jy(e,t,a),s=F(e,o);await j(s,o);try{let c=await Yy(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await fe(o,n,{containedRoot:s,beforeCommit:i?.beforeCommit}),a}function Xy(e,t){for(let r of t.artifacts){let i=zp(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function b_(e,t){let r=Ky(t,t.change),i=await Yy(e,r.change,r.manifestHash),n=G(JSON.stringify({summary:r.summary,nextAction:r.nextAction,artifacts:i.artifacts}));if(r.inputHash!==n||r.artifactCount!==i.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=zy(e,t.change),o=F(e,a);await j(o,a),await fe(a,r,{containedRoot:o})}async function k_(e){let t;try{t=await H2(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:zy(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await Yy(e.paths,e.name,t.manifestHash);let a=G(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await O2(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Jy(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}it();async function Qy(e,t,r){let i=await Ca(e,t);if(!i)return null;if(await N_(e,i.change,i.manifest)!==i.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Fl(e,i.nextState,i.previousState.revision,{allowPendingCheckpointRecovery:!0}),await r?.afterStateWritten?.(i),await b_(e,i.checkpoint),await r?.afterProgressWritten?.(i),await D2.rm(Pa(e,t),{force:!0}),i}async function S_(e,t,r){return $(e,`continue checkpoint ${t}`,()=>Mi(e,t,`continue checkpoint ${t}`,async()=>(await oc(e,t),Qy(e,t,r))))}async function Hu(e,t){await oc(e,t),await Qy(e,t)}Oe();Ws();Q();Ir();import{constants as Zy,promises as Gr}from"node:fs";import lc from"node:path";var B2=/^[a-f0-9]{64}$/u,q2=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ho=512*1024;function F2(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function fp(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wr(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function M2(e,t){let r=lc.resolve(e),i=lc.resolve(t);if(!q(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...lc.relative(r,i).split(lc.sep).filter(Boolean)]){o&&(a=lc.join(a,o));let s=await Gr.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Gr.realpath(a);if(n.length>0&&!q(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function E_(e){for(let t of e){let r=await Gr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!F2(t,r)||await Gr.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function R_(e){if(!B2.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function L2(e){let t=q2.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function P_(e,t,r){return Jn(V(e,t),R_(r))}async function V2(e,t,r){let i=await M2(r,lc.dirname(e)),n=await Gr.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ho)throw new Error(`Native check receipt exceeds ${Ho} bytes`);let[a,o]=await Promise.all([Gr.realpath(t),Gr.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Zy.O_RDONLY|Zy.O_NOFOLLOW|Zy.O_NONBLOCK,c=await Gr.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Gr.lstat(e),Gr.realpath(e)]);if(await E_(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!fp(n,l)||!fp(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,v=Buffer.allocUnsafe(16*1024);for(;;){let w=Ho+1-p,S=await c.read(v,0,Math.min(v.length,w),null);if(S.bytesRead===0)break;if(p+=S.bytesRead,p>Ho)throw new Error(`Native check receipt exceeds ${Ho} bytes`);f.push(Buffer.from(v.subarray(0,S.bytesRead)))}let[h,m,g]=await Promise.all([c.stat(),Gr.lstat(e),Gr.realpath(e)]);if(await E_(i),!m.isFile()||m.isSymbolicLink()||g!==o||!q(a,g)||!fp(l,h)||!fp(l,m))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function hp(e,t,r){let i=L2(r),n=V(e,t),a=P_(e,t,i),o=F(e,a);await j(o,a);let s=un(await V2(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}async function C_(e){let t=un(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let r=R_(t.receiptHash),i=P_(e.paths,e.name,t.receiptHash);if(Buffer.byteLength(JSON.stringify(t,null,2)+`
|
|
279
|
+
`,"utf8")>Ho)throw new Error(`Native check receipt exceeds ${Ho} bytes`);let a=F(e.paths,i);await j(a,i);try{let s=await hp(e.paths,e.name,r);if(JSON.stringify(s)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return r}catch(s){if(s.code!=="ENOENT")throw s}await fe(i,t,{containedRoot:a});let o=await hp(e.paths,e.name,r);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return r}zr();it();nn();var Du=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};na();Js();sn();var fee=64*1024;var hee=3600*1e3;var pee=z2(W2);async function x_(e,t){if(t.phase!=="verify")throw new Error(`Native verification receipt issuance requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native verification receipt issuance requires an implementation scope");let[r,i]=await Promise.all([fn(e,t.name,t.implementation_scope),kn({changeDir:se(e,t.name),briefRef:t.brief,specChanges:t.spec_changes})]);if(r.scope.contractHash!==i.contract.contractHash)throw new Error("Native verification receipt contract/scope mismatch");let n=t.run_id?`run:${t.run_id}`:`scope:${r.scope.scopeHash}`;return{bindings:{change:t.name,sourceRevision:t.revision,contractHash:i.contract.contractHash,scopeHash:r.scope.scopeHash,snapshotHash:r.scope.currentProjectionHash,artifactHash:Ih(r.scope.declaredArtifacts)},acceptanceIds:i.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${n}`,implementationExecutionId:n,scope:r}}var J2=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function eN(e,t){let r=[];for(let i of J2){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}function G2(e,t){return eN(e,t).ok}async function A_(e){let t=await x_(e.paths,e.state),r=e.checkReceipt.stale||e.checkReceipt.issues.some(o=>["scan-limit","scope-mismatch","unsafe-file","binary-skipped"].includes(o.kind)),i=e.checkReceipt.status==="passed"?"passed":r?"blocked":"failed",n=PC({kind:"static-inspection",role:"required-check",status:i,bindings:t.bindings,acceptanceIds:[],actor:`native-runtime:${e.checkReceipt.checker.policy}`,issuedAt:e.checkReceipt.endedAt,evidence:{subjects:bo({baseline:t.scope.baseline,current:t.scope.current,declaredArtifacts:t.scope.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0).map(o=>o.path).sort(),rule:e.checkReceipt.checker.policy,resultSummary:i==="passed"?"The built-in scoped inspection passed without skipped or blocking input.":`The built-in scoped inspection recorded ${e.checkReceipt.counts.issueCount} blocking issue(s).`,checkReceiptRef:e.checkReceiptRef,checkReceiptHash:e.checkReceipt.receiptHash}}),a=await Cw({paths:e.paths,name:e.state.name,receipt:n});return{receipt:n,ref:a}}function U2(e){let{receipt:t,checkReceipt:r,context:i}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!G2(t,i.bindings)||r.status!=="passed"||r.stale)return!1;let n=bo({baseline:i.scope.baseline,current:i.scope.current,declaredArtifacts:i.scope.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return r.change===i.bindings.change&&r.sourceRevision===i.bindings.sourceRevision&&r.contract.expectedHash===i.bindings.contractHash&&r.contract.beforeHash===i.bindings.contractHash&&r.contract.afterHash===i.bindings.contractHash&&r.implementation.scopeHash===i.bindings.scopeHash&&r.implementation.expectedSnapshotHash===i.bindings.snapshotHash&&r.implementation.beforeSnapshotHash===i.bindings.snapshotHash&&r.implementation.afterSnapshotHash===i.bindings.snapshotHash&&r.counts.filesSelected===n.length&&r.counts.filesScanned+r.counts.binaryFilesSkipped===n.length&&r.counts.bytesScanned===a&&r.counts.issueCount===0&&r.counts.recordedIssueCount===0&&r.issues.length===0&&!r.issuesTruncated}async function __(e){let t=await xw(e.paths,e.state.name);if(t.length===0)return null;let r=[];for(let a of t)try{let o=await Eo(e.paths,e.state.name,a);o.kind==="static-inspection"&&o.role==="required-check"&&o.status==="passed"&&r.push({ref:a,receipt:o})}catch{}if(r.length===0)return null;let i;try{if(i=await x_(e.paths,e.state),!(await Q2({paths:e.paths,context:i})).matched)return null}catch{return null}let n=null;for(let{ref:a,receipt:o}of r)try{let s=await tN({paths:e.paths,state:e.state,receipt:o});if(s===null||!U2({receipt:o,checkReceipt:s,context:i}))continue;let c={receipt:o,ref:a,checkReceipt:s,checkReceiptRef:o.evidence.checkReceiptRef};(n===null||c.receipt.issuedAt>n.receipt.issuedAt||c.receipt.issuedAt===n.receipt.issuedAt&&c.ref>n.ref)&&(n=c)}catch{}return n}function K2(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}var Y2=20;function X2(e,t){let r=[],i=0,n=0,a=0;for(;n<e.entries.length||a<t.entries.length;){let o=e.entries[n],s=t.entries[a],c=o===void 0?1:s===void 0||o.path<s.path?-1:o.path>s.path?1:0,l=c<=0?o:void 0,u=c>=0?s:void 0;if(c<=0&&(n+=1),c>=0&&(a+=1),l&&u&&l.hash===u.hash&&l.size===u.size)continue;let d=l?.path??u?.path;d&&(i+=1,r.length<Y2&&r.push({path:d,kind:l?u?"modified":"removed":"added"}))}return{changedPaths:r,changedPathCount:i,changedPathsTruncated:r.length!==i}}async function Q2(e){let t=K2(e.context.scope.baseline),r=await Es(e.paths,t,{origin:"explicit",now:e.now}),i=Fs({baseline:t,current:r,contractHash:e.context.bindings.contractHash,declaredArtifacts:e.context.scope.scope.declaredArtifacts,noCodeReason:e.context.scope.scope.noCodeReason,gitChangedPaths:e.context.scope.authority.gitChangedPaths,externalDrift:e.context.scope.authority.externalDrift}),n=X2(e.context.scope.current,i.current);return{expectedScopeHash:e.context.bindings.scopeHash,actualScopeHash:i.scope.scopeHash,expectedSnapshotHash:e.context.bindings.snapshotHash,actualSnapshotHash:i.scope.currentProjectionHash,matched:i.scope.currentProjectionHash===e.context.bindings.snapshotHash&&i.scope.scopeHash===e.context.bindings.scopeHash,...n}}async function tN(e){if(e.receipt.kind!=="static-inspection")return null;let t=await hp(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}Js();var xa=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function Z2(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function ez(e){let t=Z2(e.bundle.baseline),r=await Es(e.paths,t,{origin:"explicit",now:e.now});return Fs({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function T_(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await fn(e.paths,e.state.name,e.state.implementation_scope),r=await kn({changeDir:se(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await ez({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function j_(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await T_(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function tz(e){let t=await re({root:se(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:CE(t.text)}}function rz(e){let{receipt:t,implementationScope:r}=e,i=[],n=bo({baseline:r.baseline,current:r.current,declaredArtifacts:r.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function iz(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Ih(e.implementationScope.scope.declaredArtifacts)}}async function I_(e){let t=await Eo(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=eN(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new xa([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await tN({paths:e.paths,state:e.state,receipt:t});if(n){let a=rz({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function nz(e){let t=iz({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await I_({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof xa)return r.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await I_({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof xa)return r.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new xa(r)}function rN(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function pp(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:rN(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([T_(e),Ro(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:rN(e.state.verification_result,"stale"),envelope:null};let i=await tz({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await nz({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:rN(e.state.verification_result,"invalid"),envelope:null}}}Lr();function oz(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function O_(e){try{return await az.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function sz(e,t){try{return(await re({root:e,ref:t})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function cz(e,t,r){let i=ca(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=$_.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await sz(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await re({root:se(e,t),ref:r.source})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function lz(e,t){return O_(Mt(e,t))}async function mp(e){let t=e.now??new Date,r=await Be(e.paths,e.name),i=await Dt(e.paths,e.name),n=await X(e.paths.projectRoot),a=oz(r.name,t),o=$_.resolve(e.paths.nativeRoot,...a.split("/"));if(!q(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,p]=await Promise.all([Promise.all(r.spec_changes.map(v=>cz(e.paths,r.name,v))),pp({paths:e.paths,state:r,now:t}),ip(e.paths,r.name),js(e.paths,r.name),$s(e.paths,r.name),lz(e.paths,r.name),O_(o)]);return HA({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:p,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}qr();Yt();import{promises as iN}from"node:fs";import Sn from"node:path";var uz="comet.native.archive-tree.v1",dz={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function B_(e){let t={...dz,...e};for(let[r,i]of Object.entries(t))if(!Number.isSafeInteger(i)||i<=0)throw new Error(`Native Archive content limit ${r} must be a positive safe integer`);return t}function H_(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,r)=>t.name.localeCompare(r.name)))}function D_(e,t,r,i){if(r.entryCount+=1,r.entryCount>i.maxEntries)throw new Error(`Native Archive content exceeds ${i.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>i.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${i.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(r.manifestBytes+=n+(e.length===0?0:1),r.manifestBytes+2>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);e.push(t)}async function q_(e,t,r,i,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await lr({root:e,directory:t,label:`Native Archive content directory ${Sn.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=H_(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Sn.join(t,u.name),f=Sn.relative(e,d).replaceAll("\\","/"),p=await iN.lstat(d);if(u.isSymbolicLink()||p.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&p.isDirectory()){D_(r,{ref:f,kind:"directory"},i,n),await q_(e,d,r,i,n,a+1);continue}if(!u.isFile()||!p.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await Te({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(i.totalBytes+=v.size,i.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);D_(r,{ref:f,kind:"file",hash:v.hash,size:v.size},i,n),await o.verify()}await o.verify();let l=await lr({root:e,directory:t,label:`Native Archive content directory ${Sn.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(H_(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Sn.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function F_(e,t={}){let r=B_(t);e=Sn.resolve(e);let i=await iN.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await q_(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},r,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);return G(`${uz}\0${o}`)}async function gi(e,t={}){let r=B_(t);e=Sn.resolve(e);let i;try{i=await iN.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(i.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(i.isFile())return{kind:"file",hash:(await Te({root:Sn.dirname(e),file:e,maxBytes:r.maxFileBytes,label:`Native Archive transaction file ${Sn.basename(e)}`})).hash};if(i.isDirectory())return{kind:"directory",hash:await F_(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}Oe();Ir();import{promises as rr}from"node:fs";import dt from"node:path";Q();Yt();oo();var aN=16*1024*1024,fz=256*1024,hz=16*1024,Bu="comet.native.archive-cas.v1";function pz(e,t){let r="runtime/",i=t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(r.length):t,o=dt.resolve(n,...a.split("/"));if(!q(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function _t(e,t){let r=pz(e,t);return j(F(e,r),r)}function Aa(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function uc(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function vr(e){let t=await gi(e.target);if(!Aa(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${uc(t)}`);return t}async function oN(e,t){let r=await xi(e,t),i=await Te({root:e.runtimeDir,file:r.journal,maxBytes:fz,label:`Native Archive transaction journal ${t}`}),n=Vf(JSON.parse(i.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function vp(e,t,r){let i=Vf({...t,status:r}),n=await xi(e,i.id);return await fe(n.journal,i,{containedRoot:e.runtimeDir}),i}function gp(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function M_(e){return{...gp(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function _a(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function mz(e,t){return _a(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ie(e){try{return await rr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Li(e){let t=await rr.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=M_(t),i=await Te({root:F(e.paths,e.file),file:e.file,maxBytes:aN,label:e.label}),n=await rr.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!mz(r,M_(n))||i.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:gp(n),size:i.size}}function vz(e,t,r,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${r} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${r} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${r} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${r} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${r} identity ${c} is invalid`);if(n.schema!==Bu||n.operationId!==t.id||n.role!==r||n.hash!==i)throw new Error(`Archive CAS ${t.id} ${r} record is not transaction-bound`);return{schema:Bu,operationId:t.id,role:r,hash:i,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Vi(e,t,r,i){let n=await xi(e,t.id),a=dt.join(n.backups,".cas"),o=`.${dt.basename(i)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:a,originalRecord:dt.join(a,`${r.id}.original.json`),postRecord:dt.join(a,`${r.id}.post.json`),candidate:dt.join(a,`${r.id}.candidate`),originalQuarantine:dt.join(dt.dirname(i),`${o}.original`),rollbackQuarantine:dt.join(dt.dirname(i),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>j(F(e,c),c))),s}async function Ur(e){if(!await Ie(e.file))return null;let t=await Te({root:e.paths.runtimeDir,file:e.file,maxBytes:hz,label:`Archive CAS ${e.operation.id} ${e.role} record`});return vz(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function wp(e){let t=await Ur(e);if(t){if(!_a(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Ci({root:e.paths.runtimeDir,directory:dt.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Bu,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await fe(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let i=await Ur(e);if(!i||!_a(i.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return i}async function ot(e){let t=await Li({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!_a(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function gz(e){let t=await Li({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await wp({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await ot({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function wz(e){if(!await Ie(e.quarantine)||await Ie(e.target))return;let t=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rr.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[r,i]=await Promise.all([rr.lstat(e.quarantine),rr.lstat(e.target)]);if(!_a(gp(r),gp(i)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rr.unlink(e.quarantine),await t.verify()}async function z_(e){if(await Ie(e.quarantine)){await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await ot({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await ot({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rr.rename(e.target,e.quarantine),await t.verify(),await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await wz(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:r})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Do(e){if(!await Ie(e.file))return;await ot(e);let t=await br({root:F(e.paths,e.file),directory:dt.dirname(e.file),label:e.label});await t.verify(),await ot(e),await rr.unlink(e.file),await t.verify()}async function L_(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let i=await _t(e,t.target),n=await _t(e,t.backup),a=await gi(n);if(a!==null){if(!Aa(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await vr({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Zn({sourceRoot:F(e,i),source:i,targetRoot:F(e,n),target:n,maxBytes:aN,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await vr({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function J_(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let r=await Vi(e.paths,e.journal,e.operation,e.target),i=await Ur({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await Ie(r.originalQuarantine)){if(!i)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await ot({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:i,label:`Archive apply quarantine ${e.operation.target}`}),await L_(e.paths,e.operation,e.hooks),{record:i,quarantine:r.originalQuarantine}}if(!await Ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return i??=await gz({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await ot({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive apply target ${e.operation.target}`}),await L_(e.paths,e.operation,e.hooks),await z_({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:r.originalQuarantine,record:i,hooks:e.hooks}),{record:i,quarantine:r.originalQuarantine}}async function V_(e){let t=await Vi(e.paths,e.journal,e.operation,e.target);return await Ie(t.candidate)?(await Li({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Ci({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Zn({sourceRoot:F(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:aN,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function yz(e){let t=e.operation.stagedHash,r=await Vi(e.paths,e.journal,e.operation,e.target),i=await Ur({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(i&&await Ie(e.target))return await ot({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive write target ${e.operation.target}`}),await Ie(r.candidate)&&await Do({paths:e.paths,file:r.candidate,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i;if(await Ie(e.target)){let c=await V_(e),l=await Li({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Li({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!_a(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return i=await wp({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Do({paths:e.paths,file:c,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}let n=await V_(e),a=await Li({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Ci({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await ot({paths:e.paths,file:n,operation:e.operation,record:{schema:Bu,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rr.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await Li({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!_a(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return i=await wp({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Do({paths:e.paths,file:n,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}async function Nz(e,t,r,i){let n=await _t(e,r.target),a=await _t(e,r.staged);if(await vr({target:a,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let o=await Vi(e,t,r,n);(!await Ur({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await Ie(n))&&await J_({paths:e,journal:t,operation:r,target:n,hooks:i})}else{let o=await gi(n);if(o!==null&&!Aa(o,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${uc(o)}`)}await yz({paths:e,journal:t,operation:r,staged:a,target:n,hooks:i}),await vr({target:n,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function bz(e,t,r,i){let n=await _t(e,r.target);await J_({paths:e,journal:t,operation:r,target:n,hooks:i}),await vr({target:n,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function kz(e,t){let r=await _t(e,t.source),i=await _t(e,t.target),[n,a]=await Promise.all([gi(r),gi(i)]);if(!(n===null&&Aa(a,t.expectedSourceHash,"directory"))){if(!Aa(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${uc(n)}, target=${uc(a)}`);await rr.mkdir(dt.dirname(i),{recursive:!0}),await rr.rename(r,i),await vr({target:i,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function Sz(e,t,r,i){return r.type==="write"?Nz(e,t,r,i):r.type==="remove"?bz(e,t,r,i):kz(e,r)}function Ez(e){let t=0,r=!1,i=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){r=!0;continue}if(!r)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);i.push(a.id),t+=1,r=!1}return i}async function Rz(e,t,r,i){let n=await _t(e,r.target);if(r.type==="write"){let a=await _t(e,r.staged);await vr({target:a,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let o=await Vi(e,t,r,n),s=await Ur({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!s)throw new Error(`Completed Archive target ${r.target} has no CAS identity`);if(await ot({paths:e,file:n,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await vr({target:await _t(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await Ur({paths:e,file:o.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${r.target} has no original CAS identity`);if(await Ie(o.originalQuarantine))await ot({paths:e,file:o.originalQuarantine,operation:r,record:c,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`)}return}if(r.type==="remove"){await vr({target:n,expectedHash:null,label:`Completed Archive target ${r.target}`}),await vr({target:await _t(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let a=await Vi(e,t,r,n),o=await Ur({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${r.target} has no original CAS identity`);if(await Ie(a.originalQuarantine))await ot({paths:e,file:a.originalQuarantine,operation:r,record:o,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`);return}i||(await vr({target:await _t(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await vr({target:n,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function G_(e,t,r){let i=t.status==="prepared"?await vp(e,t,"applying"):t;if(i.status!=="applying")throw new Error(`Native Archive transaction ${i.id} cannot apply from ${i.status}`);let n=await ta(e,i.id),a=Ez({journal:i,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of i.operations.slice(0,a.length))await Rz(e,i,l,s);let c=o.size;for(let l of i.operations)o.has(l.id)||(l.id==="archive-change"&&await r?.beforeArchiveChangeMove?.(l),await Dr(e,i.id,"operation-started",l.id),await Sz(e,i,l,r),await Dr(e,i.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return i=await oN(e,i.id),i}async function Pz(e){try{return await ot(e),!0}catch{return!1}}async function Cz(e){await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await br({root:F(e.paths,e.target),directory:dt.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await ot({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rr.link(e.quarantine,e.target)}catch(r){throw r.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:r}):r}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await ot({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function nN(e){if(e.operation.type!=="write")return;let t=await Vi(e.paths,e.journal,e.operation,e.target);if(!await Ie(t.candidate))return;let r=await Li({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Do({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Bu,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function xz(e,t,r,i){let n=await _t(e,r.target),a=await Vi(e,t,r,n),o=r.expectedTargetHash,s=o===null?null:await Ur({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:o}),c=r.type==="write"?await Ur({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await Ie(a.candidate)&&await Ie(n)){let l=await Li({paths:e,file:a.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await Li({paths:e,file:n,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});_a(l.identity,u.identity)&&(c=await wp({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await Ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await ot({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await Ie(n)&&!(s!==null&&await Pz({paths:e,file:n,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await gi(n);if(Aa(u,o)){await nN({paths:e,journal:t,operation:r,target:n});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await z_({paths:e,operation:r,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:i})}if(o===null){if(await Ie(n))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await Ie(n)){if(!s||!await Ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await Cz({paths:e,operation:r,target:n,quarantine:a.originalQuarantine,record:s,hooks:i})}s&&await Ie(a.originalQuarantine)&&await Do({paths:e,file:a.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await Ie(a.rollbackQuarantine)&&await Do({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await nN({paths:e,journal:t,operation:r,target:n}),await vr({target:n,expectedHash:o,label:`Archive rollback target ${r.target}`})}async function Az(e,t){let r=await _t(e,t.source),i=await _t(e,t.target),[n,a]=await Promise.all([gi(r),gi(i)]);if(!(Aa(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Aa(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${uc(n)}, target=${uc(a)}`);await rr.mkdir(dt.dirname(r),{recursive:!0}),await rr.rename(i,r)}}async function U_(e,t,r){let i=await ta(e,t.id);if(i.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await vp(e,t,"rolling-back");await Dr(e,n.id,"rollback-started");let a=new Set(i.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await Az(e,o):await xz(e,n,o,r));return await Dr(e,n.id,"rollback-completed"),n=await vp(e,n,"rolled-back"),n}async function W_(e,t,r){let i=await _t(e,r.target);if(r.type==="write"){let n=await Vi(e,t,r,i),a=await Ur({paths:e,file:n.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!a)throw new Error(`Archive commit target ${r.target} has no CAS identity`);await ot({paths:e,file:i,operation:r,record:a,label:`Archive commit target ${r.target}`});return}await vr({target:i,expectedHash:null,label:`Archive commit target ${r.target}`})}async function _z(e,t){for(let r of t.operations){if(r.type==="move")continue;let i=await _t(e,r.target),n=await Vi(e,t,r,i);if(await Ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await W_(e,t,r),r.expectedTargetHash!==null){let a=await Ur({paths:e,file:n.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${r.target} has no original CAS identity`);await Ie(n.originalQuarantine)&&await Do({paths:e,file:n.originalQuarantine,operation:r,record:a,label:`Archive commit original quarantine ${r.target}`})}await nN({paths:e,journal:t,operation:r,target:i})}for(let r of t.operations)r.type!=="move"&&await W_(e,t,r)}async function yp(e,t,r){return r==="commit"&&await _z(e,t),await Dr(e,t.id,r),r==="commit"?vp(e,t,"committed"):t}Ee();Oe();Va();Ee();zr();var ote=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});qr();Qa();it();Q();Yt();oo();var Ote=16*1024*1024,Np=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},qu=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function Y_(e,t){let r=t.operations.find(i=>i.id==="archive-change");if(!r||r.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return dc.resolve(e.nativeRoot,...r.target.split("/"))}async function X_(e,t,r){let i=await ta(e,t.id);if(i.some(m=>m.type==="archive-finalized"))return;let n=i.some(m=>m.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let m=t.operations.find(w=>w.id==="archive-change");if(!m||m.type!=="move"||!m.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await gi(Y_(e,t));if(g?.kind!=="directory"||g.hash!==m.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=Y_(e,t),o=dc.join(a,lt),s=await wP(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=V(e,s.name),l=await pt(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let m=TA(qi,l,new Set,$y,void 0);if(!m.action)throw new Error(m.reason??"Native archive produced no action");u=jA(qi,m.state,{actionId:m.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},$y,void 0)}let d=G(`archive:${t.id}:${s.name}`),f=await Zt(c,u.trajectoryRef),p=f.filter(m=>m.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(m=>m.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=p.find(m=>m.type==="state_transitioned"),h={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!Iz(v.data,h)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||p.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await yp(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await ws(e,t,"archive-finalization-started")),!s.archived){let m={...s,archived:!0};await gP(o,m)}v||(v=await Sa({changeDir:c,run:u,type:"state_transitioned",data:h,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Oo({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await co(c,u),await Cu(e,s.name),t.schema==="comet.native.transaction.v2"?await yp(e,t,"archive-finalized"):await ws(e,t,"archive-finalized")}async function sN(e,t){let r=He(e,t);try{let i=await K_.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${r}`);return await j(e.runtimeDir,r),await K_.rm(r,{recursive:!0,force:!0}),null}catch(i){return i.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${i.message}`}}async function Tz(e,t,r){if(t.schema==="comet.native.transaction.v2"){if(!(await ta(e,t.id)).some(c=>c.type==="operation-started")){let c=await mp({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new qu(c,"Native Archive facts changed before the first transaction operation")}let o=await G_(e,t,{...r,beforeArchiveChangeMove:async c=>{await r?.beforeArchiveChangeMove?.(c);let l=await Be(e,t.change),u=await pp({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await X_(e,o,r);let s=await yp(e,o,"commit");return{journal:s,runtimeCleanupWarning:await sN(e,s.change)}}let i=await eR(e,t);await X_(e,i,r);let n=await ws(e,i,"commit");return{journal:n,runtimeCleanupWarning:n.change?await sN(e,n.change):null}}function jz(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(dc.resolve(t.projectRoot)!==dc.resolve(e.projectRoot)||dc.resolve(t.nativeRoot)!==dc.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function Q_(e){return $(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await Ki(e.paths,"archive",`recover archive ${e.transactionId}`);try{let r=await ur(e.paths,e.transactionId),i=r.schema==="comet.native.transaction.v2"?await oN(e.paths,e.transactionId):r;return jz(e.paths,i),i.status==="committed"?(i.change&&await sN(e.paths,i.change),i):i.status==="rolled-back"?i:e.strategy==="continue"?(await Tz(e.paths,i)).journal:i.schema==="comet.native.transaction.v2"?U_(e.paths,i):zf(e.paths,i)}finally{await Yi(t)}},{allowedTransactionId:e.transactionId})}Ee();Q();tt();function ae(e,t,r){return e==="zh-CN"?r:t}var cN={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Z_(e,t){return typeof e=="string"&&cN[e]?ae(t,cN[e].en,cN[e].zh):typeof e=="string"?e:""}function lN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function $z(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function eI(e,t){let r=[];e.failed>0&&r.push(ae(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(ae(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(ae(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=ae(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function tI(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function uN(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function Oz(e,t,r){return e==="done"?ae(r,"complete","已完成"):e==="await-user"?ae(r,"waiting for a user decision","等待用户决定"):e==="blocked"?ae(r,"paused: needs attention","已暂停,需要处理"):t?ae(r,"waiting for a user decision","等待用户决定"):ae(r,"ready to continue","可继续推进")}function Hz(e,t,r){let i=uN(e),n=[];r&&n.push(r);let a=ae(i,`Change ${e.change}`,`需求 ${e.change}`),o=Z_(e.phase,i),s=Oz(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(eI(t,i));let c=e.userCommunication,l=rI(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function rI(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:ae(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:ae(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:ae(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function Dz(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function Bz(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Z_(e.phase,t),n=e.status==="await-user"?ae(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?ae(t,"paused","已暂停"):e.status==="done"?ae(t,"complete","已完成"):ae(t,"in progress","进行中"),a=lN(e.acceptance)?`${ae(t,", ",",")}${eI(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function qz(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function Fz(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function Mz(e){if(e.healthy){let i=e.repaired?ae("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):ae("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=Lz(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:ae("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:ae("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function Lz(e){return tI(e)?rI(e,uN(e)):void 0}function iI(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(Fz(t))return Mz(t);if(Dz(t)){let i=qz(t.items);return{summary:[t.total===t.items.length?ae(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):ae(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>Bz(a,i))].join(`
|
|
280
|
+
`)}}let r=t.continuation;if(tI(r))return Hz(r,Vz(t),Wz(t,uN(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:ae(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function Vz(e){if(lN(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(lN(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return $z(r.acceptance)}return null}function Wz(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return ae(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?ae(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function nI(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:ae("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:ae("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:ae("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:ae("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:ae("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:ae("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:ae("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:ae("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:ae("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Eh();var aI=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],fN=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:aI,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec remove <change-name> <capability>
|
|
281
|
+
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
282
282
|
comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
|
|
283
283
|
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}]. Returns checkExecution with operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
284
284
|
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function dN(e,t){return`${e}:
|
|
@@ -286,30 +286,30 @@ ${t.map(r=>` ${r}`).join(`
|
|
|
286
286
|
`)}`}function zz(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return fN[r]||t.length>1&&fN[t[0]]?.subcommands?r:t[0]}function hN(e=[]){let t=zz(e),r=fN[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",dN("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...aI];return n&&n.length>0&&i.push("",dN("Options",n)),i.push("",`Output:
|
|
287
287
|
${r.output}`),r.examples&&i.push("",dN("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
288
288
|
`)}
|
|
289
|
-
`}}var Jz=hN().usage;var sI=10*1024*1024,
|
|
290
|
-
`}function W(e,t,r){return{command:e,exitCode:0,data:t,text:r??uI(t)}}function Kz(e,t){if(t instanceof
|
|
289
|
+
`}}var Jz=hN().usage;var sI=10*1024*1024,H=class extends Error{};function It(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new H(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Re(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new H(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new H(`${t} requires a value`);return e.splice(i,2),n}function Ce(e){if(e.length>0)throw new H(`Unexpected argument: ${e[0]}`)}function Qe(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new H(`${t} is required`);return r}function bp(e,t="en"){let r=Re(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new H("--language must be en or zh-CN");return r}function pN(e,t){let r=Fu.normalize(oI(e)),i=Fu.normalize(oI(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function oI(e){let t=Fu.resolve(e);try{return Gz.native(t)}catch{return t}}function Uz(e){let t=Fu.resolve(e),r=ne(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=ne(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!pN(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||pN(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:pN(process.cwd(),r.currentWorktreeRoot)?Fu.resolve(process.cwd()):r.currentWorktreeRoot}async function cI(e){return e?Uz(e):wf(process.cwd())}async function xr(e){let t=await lE({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function lI(e){let t=await X(e);return pe(e,t?.native.artifact_root??"docs")}function uI(e){return JSON.stringify(e,null,2)+`
|
|
290
|
+
`}function W(e,t,r){return{command:e,exitCode:0,data:t,text:r??uI(t)}}function Kz(e,t){if(t instanceof H)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Np)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof qu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Dl)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Is)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof ua)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ts)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof xa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Du)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function dI(e,t){let r=Kz(e,t),i=r.error;if(!i)return r;let n=nI({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function mN(e,t,r=!1){let i=e.envelope??iI(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
291
291
|
`}:e.error?{exitCode:e.exitCode,stderr:i?xA(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:CA(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==uI(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
292
292
|
${yn.details}
|
|
293
293
|
${JSON.stringify(e.data,null,2)}
|
|
294
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function hI(e,t){let r=Qe(e,"change name"),i=It(e,"--dry-run"),n=Re(e,"--expect-preflight"),a=It(e,"--confirmed"),o=Re(e,"--finish"),s=Re(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new
|
|
294
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function hI(e,t){let r=Qe(e,"change name"),i=It(e,"--dry-run"),n=Re(e,"--expect-preflight"),a=It(e,"--confirmed"),o=Re(e,"--finish"),s=Re(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new H("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new H("--finish must be merge, push, pull-request, or keep");let l=await xr(t),u=await _e(l.paths,r),d=u?await Yn(l.paths,{kind:"archive",change:r}):null,f=d?.kind==="archive"?d.journal.spec_changes.slice(0,d.journal.next_spec_index):[],p=u?!1:await tA(l.paths,r);if(u||p){if(n)throw new H("Portable Native Archive does not use preflight hashes");if(i&&a)throw new H("--confirmed is only valid when executing Archive");if(s&&s!==r)throw new H("--serial-first must name the change being archived");if(!i&&c)throw new H("--finish is only valid with --dry-run");Ce(e);let h=u&&!i&&d?.kind!=="archive"?await jo({paths:l.paths,name:r}):null,m=h?.state??(u?await L(l.paths,r):null);if(h?.action==="reverify"||h?.action==="await-user")return W(i?"archive --dry-run":"archive",{archived:!1,state:h.state,recovery:h,continuation:U(h.state)},`${h.message}
|
|
295
295
|
`);if(i){if(!m)return W("archive --dry-run",{change:r,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",r,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${r}
|
|
296
|
-
`);c&&(m=await Vx({paths:l.paths,name:r,finish:c}));let y=await fy({paths:l.paths,name:r}),E="capabilities are also declared by:",P=y.blockers.filter(oe=>!oe.startsWith(E)),b=[],k=m.workspace.isolation!=="current"&&m.workspace.finish===null;if(k&&P.push("Native branch and worktree isolation require a workspace finish choice"),!k)try{await tp({paths:l.paths,state:m,appliedSpecChanges:f,pullRequestFinish:l.config.native.finish?.pull_request})}catch(oe){let ce=oe.message;P.push(ce),b.push({message:ce,paths:oe instanceof wn?oe.paths:[],workspaceRoot:oe instanceof wn?oe.workspaceRoot:l.paths.projectRoot})}let R=y.capabilityPeers.length>0&&s!==r,I=R&&P.length===0?
|
|
297
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new
|
|
298
|
-
`)}if(s)throw new
|
|
299
|
-
`)}Ee();Ee();Ws();import{createHash as Yz}from"node:crypto";import{constants as vN,promises as
|
|
300
|
-
`);for(let n=0;n<i.length;n+=1){let a=i[n].endsWith("\r")?i[n].slice(0,-1):i[n],o=n+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&r({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&r({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&r({path:e,line:o,kind:"space-before-tab"})}}async function aJ(e){if(e.state.partial_allowance===null)return new Set;let t=await du(e.paths,e.state.name,e.state.partial_allowance),r=e.scope.scope.unresolvedScopes.map(i=>i.id).sort();if(t.change!==e.state.name||t.scopeHash!==e.scope.scope.scopeHash||JSON.stringify(t.scopeIds)!==JSON.stringify(r))throw new Error("Native partial allowance does not match the current implementation scope");return new Set(t.scopeIds)}async function wI(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await
|
|
301
|
-
`}}import{promises as fT}from"node:fs";import Bp from"node:path";import{promises as Op}from"fs";import bt from"path";Ee();tt();import{promises as bJ}from"fs";pl();ct();Ee();Ps();Q();Zi();Il();async function bI(e,t){let r=[],i=V(e,t.name),n=Jn(i,kr.stateRef),a;try{a=await pt(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Jn(i,a.trajectoryRef),s=await xs(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Zt(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Jn(i,a.checkpointRef);try{let u=await Cs(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}na();Lr();var sJ=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function cJ(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function lJ(e){return e?e.map(cJ).join(" "):null}function uJ(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function Ur(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function dJ(e){return e.map(t=>Ur(t,[],null))}function fJ(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[Ur("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(Ur("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(Ur("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Ur("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(Ur("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(Ur("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Ur("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Lt(e,t){let r=t.commandArgs===void 0?uJ(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?lJ(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??dJ(t.requiredInputs??[])}}function Sp(e){let r=(e.findings??[]).filter(d=>!As(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||sJ.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Lt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Lt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Ur("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Lt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Lt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Lt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Lt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Ur("summary",["--summary"],"<summary>")]});if(n)return Lt(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Lt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Ur("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Lt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Lt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Lt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Lt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Lt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Ur("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Lt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Lt(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=fJ(e.state);return Lt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}Ee();Q();Lr();import Mu from"path";var kI=8,hJ={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function pJ(e){let t=hJ[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:As(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function mJ(e,t,r){if(!r.path)return null;let i;if(Mu.isAbsolute(r.path)?i=Mu.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Mu.resolve(se(e,t.name),...r.path.split(/[\\/]/u)):i=Mu.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Mu.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function vJ(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function gN(e){return e.findings.map(t=>{let r=pJ(t.code);return{code:t.code,message:t.message,severity:r.severity,path:mJ(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:vJ(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function wN(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,kI),truncated:t.length>kI}}var SI=240,EI=8,Ep=50;function RI(e){let t=Array.from(e);return t.length<=SI?e:`${t.slice(0,SI-1).join("")}…`}function gJ(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function wJ(e){let t=[...new Set(e.map(gJ))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,EI),reasonCount:e.length,codesTruncated:t.length>EI};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Ep),reasonsTruncated:e.length>Ep}}}async function PI(e){let t=null;try{let s=await Ca(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Pa(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Pa(e.paths,e.state.name)}}let r=await k_({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=wJ(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ra.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:RI(r.checkpoint.summary),nextAction:RI(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ra.maxArtifacts}}Q();zr();Zi();Js();on();async function yJ(e,t){let r=V(e,t.name),i=await pt(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Cs(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Zt(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function NJ(e,t){let r=await yJ(e,t);return{committed:r,latest:QA(r),history:XA(r)}}async function CI(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await NJ(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}zr();Lr();Yt();Q();var kJ=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ar=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function yN(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function SJ(e){return(await Ru(e))?.change??null}function EJ(e,t,r=!1,i){return Sp({state:e,archiveReady:t,evidenceRetreat:r}).command}async function RJ(e,t){let r=se(e,t.name),i=[...(await Wg(r,t.brief)).findings,...(await EP(e,t)).findings,...await bI(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Rs(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Qf(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await kn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await bn(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await zg(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function Ia(e,t,r){let i=await SJ(e)===t,n=await ll(e,t),a=await $l(e,t),o;try{let k=await Vr(e,t);if(k.status==="migration-required"&&k.state)return{name:t,phase:k.state.phase,revision:"revision"in k.state?k.state.revision:null,approval:k.state.approval,verificationResult:k.state.verification_result,specChanges:k.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:k.schema,migrationRequired:!0,minimumRuntimeVersion:k.minimumRuntimeVersion,error:k.message};if(k.status!=="current"||!k.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:k.schema,minimumRuntimeVersion:k.minimumRuntimeVersion,error:k.message??`Native change ${t} is incompatible`};o=k.state}catch(k){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:k.message}}if(n.status!=="available"){let k={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},R=gN({paths:e,state:o,findings:[k]}),I=Sp({state:o,findings:R});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:I.command,archiveReady:!1,inspection:{freshness:"stale",codes:[k.code],reasonCount:1,codesTruncated:!1},findingSummary:wN(R),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:I,workspace:a,runtime:n,...r?.details?{findings:R}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:k.message}:{}}}let s=await PI({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await CI(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let k=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:k,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let k=await kn({changeDir:se(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),R=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Ne=await Ro(e,o.name,o.verification_evidence);for(let oe of Ne.acceptanceTrace.entries)R.set(oe.acceptanceId,oe.status==="failed"?"failed":oe.status==="missing"?"missing":"satisfied")}let I=EE({criteria:k.contract.acceptance,acceptanceHash:k.contract.acceptanceHash,verificationStatuses:R,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),C=I.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",I.nextCursor,"--project-root",e.projectRoot]:null;u={...I,...C?{nextPageCommand:yN(C),nextPageArgs:C}:{}}}catch(k){if(r.acceptanceCursor)throw k;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let k=await ip(e,o.name,{tolerateInvalidSiblings:!0});d.push(...k.findingCodes.map(R=>({code:R,message:`Native change overlap is visible in the current root: ${R}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let k=await Dt(e,o.name);if(k)if(k.schema==="comet.native.workspace.v3"){let R=await Ai({paths:e,identity:k});R.state==="drifted"&&R.code&&f.push({code:R.code,message:R.message??"Native workspace binding is no longer valid"})}else{let R=await sa({paths:e,identity:k});f.push(...R.findingCodes.map(I=>({code:I,message:`Native workspace advisory changed: ${I} (${R.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let k=await j_({paths:e,state:o});v=k.freshness!=="fresh",p.push(...k.findingCodes.map(R=>({code:R,message:`Native Verify implementation scope is not current: ${R}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await mp({paths:e,name:o.name}),m.push(...h.findingCodes.map(k=>({code:k,message:`Native Archive is blocked: ${k}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await RJ(e,o),...s.findings,...d,...f,...p,...l,...m].filter((k,R,I)=>I.findIndex(C=>C.code===k.code&&C.path===k.path)===R),w=gN({paths:e,state:o,findings:g}),S=w.filter(k=>!As(k.code)),N=o.phase==="archive"&&h?.ready===!0&&S.length===0,y=v||o.phase==="archive"&&(h?.findingCodes??[]).some(k=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(k)),E=w.some(k=>k.code==="trajectory-tail-incomplete"||k.code==="trajectory-invalid"||k.requiredAction==="return-to-bound-working-directory"||k.requiredAction==="repair-workspace-binding"),P=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",b=w.find(k=>k.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:E||P?null:EJ(o,N,y,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:wN(w),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Sp({state:o,findings:w,archiveReady:N,evidenceRetreat:y,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:w.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Ep,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:w.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...b?{error:b.message}:{}}}async function NN(e){let t;try{t=await br({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await bJ.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Ar.maxChanges))throw new Error(`Native status exceeds ${Ar.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}function Rp(e,t){let r=t.toString(36),i=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${r}.${i}`}function PJ(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=kJ.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let i=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:r});if(t[3]!==i)throw new Error("Native status cursor integrity check failed");return r}async function CJ(e,t){let r=await NN(e),i=D("comet.native.status-names.v1",r),n=PJ({namesHash:i,total:r.length,cursor:t?.cursor}),a=await Promise.all(r.slice(n,n+Ar.maxItems).map(u=>Ia(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,p={schema:"comet.native.status-page.v1",total:r.length,offset:n,items:d,nextCursor:f<r.length?Rp(i,f):null,nextPageCommand:f<r.length?yN(["comet","native","status","--cursor",Rp(i,f)]):null,nextPageArgs:f<r.length?["comet","native","status","--cursor",Rp(i,f)]:null,limits:{...Ar}};if(Buffer.byteLength(JSON.stringify(p),"utf8")>Ar.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<r.length?Rp(i,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:r.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?yN(l):null,nextPageArgs:l,limits:{...Ar}}}async function bN(e,t){return(await CJ(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}Ws();Ee();import{createHash as JJ,randomUUID as GJ}from"node:crypto";import{constants as PN,promises as Se}from"node:fs";import qe from"node:path";tt();zr();it();Q();var xp=Ha(Mn(),1);$e();Ee();qr();it();Q();Yt();import{randomUUID as xJ}from"crypto";import{promises as TI}from"fs";import SN from"path";import{isDeepStrictEqual as EN}from"util";Zi();na();wl();var qo=/^[a-f0-9]{64}$/u,AJ=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),_J=new Set(["sourceHash","targetHash","nextJournal"]),IJ=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),xI=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),TJ=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Pp(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function AI(e){return JSON.stringify(e,null,2)+`
|
|
302
|
-
`}function RN(e){return e.schema===Xe?fh(e):lo(e)}function kN(e,t){return{...e,schema:Xe,minimum_runtime_version:2,revision:t}}function jJ(e){return{...e,schema:
|
|
303
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(i&&a.schema===Xe?fc(a,u.previousState)||fc(a,u.nextState):a.schema===Ye&&(II(a,u.previousState)||II(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(i&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(r.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ye)throw new Error("Schema migration transition supersede target schema is invalid");s=OJ(r.transitionSupersede,t,a,r.id)}let c;if(r.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!r.runRetreat||typeof r.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Pp(r.runRetreat,TJ,"Schema migration Run retreat");let l=r.runRetreat,u,d;try{u=oa(l.previousRun),d=oa(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!qo.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ye||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:r.id,change:t,fromSchema:r.fromSchema,toSchema:r.toSchema,sourceHash:r.sourceHash,targetHash:r.targetHash,createdAt:r.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Vu(e,t){let r=Lu(e,t),i=F(e,r);await j(i,r);try{let n=await Bf({root:i,file:r,maxBytes:524288,label:"Native schema migration journal"});return HJ(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function DJ(e,t,r){let i=await Rs(e,t),n=i?await Qf(e,i):await Zf(e,{now:new Date(r),origin:"legacy-migration"});if(!n.complete){let a=Rg(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new Ts(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}i===null&&await Cg(e,t,n)}async function jI(e){try{return await Br(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function BJ(e,t){let r=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:r.nextRun.runId,data:{...r.eventData,migrationId:e.id,evidenceHash:r.evidenceHash}}}async function $I(e,t){let r=t.transitionSupersede,i=V(e,t.change),n=await Zt(i,r.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!EN(o.event,BJ(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function qJ(e,t,r){if(!t.transitionSupersede)return;let i=Mt(e,t.change),n=await jI(i);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=V(e,t.change),o=await pt(a),s=await $I(e,t),c=await Cs(a,t.transitionSupersede.nextRun.checkpointRef);if(!r||!o||!En(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==G(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function FJ(e,t,r){let i=t.transitionSupersede;if(!i)return;let n=V(e,t.change),a=await pt(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!En(a,i.nextRun)){if(!En(a,i.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await co(n,i.nextRun),await r?.afterRunStateWritten?.(t)}if(!En(await pt(n),i.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await $I(e,t);if(o.sequence===null){let l=await Sa({changeDir:n,run:i.nextRun,type:"state_migrated",data:{...i.eventData,migrationId:t.id,evidenceHash:i.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await r?.afterTrajectoryWritten?.(t),await Oo({changeDir:n,run:i.nextRun,trajectoryOffset:o.sequence,evidenceHash:i.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t);let s=Mt(e,t.change),c=await jI(s);if(c!==null){if(c!==i.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await TI.rm(s),await r?.afterTransitionSuperseded?.(t)}}async function MJ(e,t,r){if(!t.runRetreat)return;let i=V(e,t.change),n=await pt(i);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!En(n,t.runRetreat.nextRun)){if(!En(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await co(i,t.runRetreat.nextRun),await r?.afterRunStateWritten?.(t)}let a=await Zt(i,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Sa({changeDir:i,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await r?.afterTrajectoryWritten?.(t),await Oo({changeDir:i,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t)}async function LJ(e,t,r){let i=await Vu(e,t);if(!i)return null;if(await $s(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=SN.join(se(e,t),lt),a=await Br(n);if(await qJ(e,i,a===i.targetHash),await DJ(e,t,i.createdAt),a!==i.targetHash){if(a!==i.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${i.sourceHash}, actual ${a}`);await xe(n,(0,xp.stringify)(RN(i.nextState))),await r?.afterStateWritten?.(i)}if(i.transition){let o=Mt(e,t),s=await Br(o);if(s!==i.transition.targetHash){if(s!==i.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${i.transition.sourceHash}, actual ${s}`);await fe(o,i.transition.nextJournal),await r?.afterTransitionWritten?.(i)}}return await FJ(e,i,r),await MJ(e,i,r),await TI.rm(Lu(e,t),{force:!0}),i.nextState}async function VJ(e){let t=V(e.paths,e.state.name),r=await pt(t);if(!r||r.runId!==e.state.run_id||r.currentStep!==e.state.phase||r.currentStep!=="verify"&&r.currentStep!=="archive"||r.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let i={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},n=G(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:r,nextRun:i,evidenceHash:n,eventData:{fromSchema:Xe,toSchema:Ye,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function WJ(e){let{journal:t,state:r}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=fc(r,t.previousState),a=fc(r,t.nextState);if(!n&&!a)throw new Error(`Native change ${r.name} does not match its v2 evidence transition`);let o=V(e.paths,r.name),s=await pt(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${r.name}`);let c=t.previousRun!==null&&En(s,t.previousRun),l=En(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${r.name}`);let d=(await Zt(o,t.nextRun.trajectoryRef)).map((g,w)=>({event:g,index:w})).filter(({event:g})=>g.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!EN(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Cp(r),revision:r.revision+(r.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=G(JSON.stringify({operation:"supersede-v2-evidence-transition",change:r.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Br(Mt(e.paths,r.name)),transitionId:t.id,previousRun:v,nextRun:h,evidenceHash:m,eventData:{fromSchema:Xe,toSchema:Ye,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function zJ(e){let t,r,i,n;if(e.state.schema===Kt){if(t=kN(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==to)throw new Error("Native v1 change has a transition from another schema generation");let s=jJ(e.pendingTransition.journal);if(_I(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(_I(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Mt(e.paths,e.name);r={sourceHash:await Br(c),targetHash:G(AI(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Xi)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await WJ({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,i=l.plan}else{let l=$J(s);if(fc(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(fc(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Mt(e.paths,e.name);r={sourceHash:await Br(u),targetHash:G(AI(l)),nextJournal:l}}}else t=Cp(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await VJ({paths:e.paths,state:e.state,migrationId:e.id}));let a=SN.join(se(e.paths,e.name),lt),o=(0,xp.stringify)(RN(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Kt?Xe:Ye,sourceHash:await Br(a),targetHash:G(o),createdAt:e.now.toISOString(),nextState:t,...r?{transition:r}:{},...i?{transitionSupersede:i}:{},...n?{runRetreat:n}:{}}}async function OI(e){return $(e.paths,`migrate schema for ${e.name}`,()=>Fi(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let r=await LJ(e.paths,e.name,e.hooks);if(r?.schema===Ye)return r;let i=await Vr(e.paths,e.name);if(i.status==="current"&&i.state)return i.state;if(i.status!=="migration-required"||!i.state)throw new Error(i.message??`Native change ${e.name} cannot be migrated`);if(await $s(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=i.state;if(n.schema!==Kt&&n.schema!==Xe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Vy(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await zJ({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??xJ()}),s=Lu(e.paths,e.name),c=F(e.paths,s);await j(c,s),await fe(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}oo();Ir();on();au();Js();var Rn=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),UJ=512*1024,Fo=/^([a-f0-9]{64})\.json$/u,KJ=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,YJ=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Ap=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function xN(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vi(e,t){return xN(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function FI(e,t){return xN(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function hc(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ir(e,t){return e<t?-1:e>t?1:0}function XJ(e,t){let r=qe.relative(e.projectRoot,t);if(r.length===0||qe.isAbsolute(r)||r===".."||r.startsWith(`..${qe.sep}`))throw new Error("Native evidence retention finding path is outside the project");return r.split(qe.sep).join("/")}function MI(e,t){return qe.join(V(e,t),"evidence")}function _p(e,t){return XJ(e,MI(e,t))}async function Ip(e,t){let r=qe.resolve(e),i=qe.resolve(t);if(!q(r,i))throw new Error("Native evidence retention path escapes its managed change");let n=qe.relative(r,i).split(qe.sep).filter(Boolean),a=[],o=r;for(let s of["",...n]){s&&(o=qe.join(o,s));let c=await Se.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Se.realpath(o);if(a.length>0&&!q(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...hc(c)})}return a}async function Kr(e){for(let t of e){let r=await Se.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xN(t,r)||await Se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function LI(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:di(e,t)}function HI(e){return e!==null&&YJ.test(e)?[e]:[]}function QJ(e,t,r,i){if(e==="snapshots")return{canonical:qs(r,t),dependencies:[]};if(e==="scopes"){let a=Ms(r);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Ch(r);if(a.change!==i||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[di("scopes",a.scopeHash)]}}if(e==="verifications"){let a=nu(r);if(a.change!==i||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(HI));return{canonical:a,dependencies:[a.implementationScopeRef,kw(a.reportHash),...HI(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Native report evidence must be an object");let a=r;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||JJ("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=cu(r);if(a.bindings.change!==i||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=ln(r);if(n.change!==i||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Ta(e){let t=await Se.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let r=e.kind==="check-receipts"?UJ:Wr;if(t.size>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let i=await Se.realpath(e.file);if(!q(e.directoryChain[0].realPath,i))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":PN.O_RDONLY|PN.O_NOFOLLOW|PN.O_NONBLOCK,a=await Se.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Se.lstat(e.file),Se.realpath(e.file)]);if(await Kr(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==i||!Vi(hc(t),o)||!Vi(hc(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let w=r+1-d,S=await a.read(u,0,Math.min(u.length,w),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,p,v]=await Promise.all([a.stat(),Se.lstat(e.file),Se.realpath(e.file)]);if(await Kr(e.directoryChain),!p.isFile()||p.isSymbolicLink()||v!==i||!Vi(hc(o),f)||!Vi(hc(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(h)}catch(w){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:w})}let g=QJ(e.kind,e.hash,m,e.name);if(h!==JSON.stringify(g.canonical,null,2)+`
|
|
304
|
-
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:hc(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(ir)}}finally{await a.close()}}async function DI(e){try{return await Se.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function ZJ(e){let t=V(e.paths,e.name),r=t,i=MI(e.paths,e.name);await j(F(e.paths,i),i);let n;try{let s=await Ip(t,i);n=await Se.readdir(i,{withFileTypes:!0}),await Kr(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Ap){if(!n.some(f=>f.name===s))continue;let c=qe.join(i,s),l=await Ip(t,c),u=(await Se.readdir(c,{withFileTypes:!0})).sort((f,p)=>ir(f.name,p.name)),d=new Map;for(let f of u){let p=KJ.exec(f.name);if(!p)continue;let v=d.get(p[1])??[];v.push(f),d.set(p[1],v)}for(let[f,p]of[...d.entries()].sort(([v],[h])=>ir(v,h))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=p[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let h=qe.join(c,f),m=Fo.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let g=LI(s,m),w=qe.join(c,v.name),S=await Ta({changeRoot:r,file:w,ref:g,kind:s,hash:m,name:e.name,directoryChain:l}),N=await DI(h),y=N?null:await Ta({changeRoot:r,file:h,ref:g,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:g,original:h,quarantine:w,document:S,action:N?"restore-original":"finish-linked-recovery",originalDocument:y})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(ir);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:pc(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Tp(o)}`),path:_p(e.paths,e.name)}]};for(let s of a.sort((c,l)=>ir(c.ref,l.ref))){if(await Kr(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ta({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ta({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Vi(s.originalDocument.identity,d.identity)||!Vi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Se.rm(s.quarantine),await Kr(s.document.directoryChain);continue}if(!await DI(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Se.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Vi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Se.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ta({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ta({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!FI(s.document.identity,l.identity)||!Vi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Se.rm(s.quarantine),await Kr(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:pc(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Tp(o)}`),path:_p(e.paths,e.name)}]}}async function eG(e,t){let r=V(e,t),i=r,n=qe.join(r,"evidence");await j(F(e,n),n);let a;try{let l=await Ip(r,n);a=await Se.readdir(n,{withFileTypes:!0}),await Kr(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Ap.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(ir);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Tp(o)}`);let s=[],c=0;for(let l of Ap){if(!a.some(p=>p.name===l))continue;let u=qe.join(n,l),d=await Ip(i,u),f=(await Se.readdir(u,{withFileTypes:!0})).sort((p,v)=>ir(p.name,v.name));await Kr(d);for(let p of f){if(s.length>=Rn.maxDocuments)throw new Error(`Native evidence store exceeds ${Rn.maxDocuments} documents`);let v=Fo.exec(p.name);if(!v||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let h=LI(l,v[1]),m=qe.join(u,p.name);await j(F(e,m),m);let g=await Ta({changeRoot:i,file:m,ref:h,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=g.size,c>Rn.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Rn.maxScannedBytes} scanned bytes`);s.push(g)}await Kr(d)}return s}function BI(e,t){let r=new Set,i=[...e].sort(ir).reverse();for(;i.length>0;){let n=i.pop();if(r.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);r.add(n);for(let o of[...a.dependencies].sort(ir).reverse())r.has(o)||i.push(o)}return r}function tG(e){let t=new Map(e.map(a=>[a.ref,a])),r=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&r.set(o,(r.get(o)??0)+1);let i=[...r].filter(([,a])=>a===0).map(([a])=>a).sort(ir),n=[];for(;i.length>0;){let a=i.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=r.get(s);if(c===void 0)continue;let l=c-1;r.set(s,l),l===0&&(i.push(s),i.sort(ir))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function rG(e,t,r){let i=new Map(e.map(c=>[c.ref,c]));if(i.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!i.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=BI(t,i),a=new Set(n);for(let c of e)r-c.mtimeMs<Rn.minimumAgeMs&&a.add(c.ref);for(let c of Ap){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||ir(u.ref,d.ref)).slice(0,Rn.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=BI(a,i),s=e.filter(c=>!o.has(c.ref)&&r-c.mtimeMs>=Rn.minimumAgeMs).sort((c,l)=>ir(c.ref,l.ref));return{candidates:tG(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Tp(e){let t=e.slice(0,Rn.maxReportedRefs),r=e.length-t.length;return`${t.join(", ")}${r>0?`, ... (${r} more)`:""}`}function pc(e){let t=Rn.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let r=e;for(;r.length>0&&Buffer.byteLength(`${r}...`,"utf8")>t;)r=r.slice(0,-1);return`${r}...`}function CN(e,t,r,i){let n=t.candidates.map(a=>a.ref).sort(ir);return{severity:"info",code:r?"evidence-retention-cleaned":"evidence-retention-candidates",message:pc(`${r?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Tp(n)}`),path:i}}async function qI(e,t){try{await Se.lstat(t);return}catch(r){if(r.code!=="ENOENT")return}try{await Se.rename(e,t)}catch{}}async function iG(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Kr(e.directoryChain);let r=await Ta({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Fo.exec(qe.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),i=await Se.lstat(e.file),n=await Se.realpath(e.file);if(!i.isFile()||i.isSymbolicLink()||!Vi(e.identity,i)||!Vi(e.identity,r.identity)||!q(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=qe.join(qe.dirname(e.file),`.${qe.basename(e.file)}.${GJ()}.gc`);await Se.rename(e.file,a);try{let[o,s]=await Promise.all([Se.lstat(a),Se.realpath(a)]);if(await Kr(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!FI(e.identity,o)||!q(e.directoryChain[0].realPath,s))throw await qI(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Se.rm(a),await Kr(e.directoryChain)}catch(o){throw await qI(a,e.file),o}}async function nG(e){if((await X(e.projectRoot))?.native.pending_root_move)return!0;let r;try{r=await Se.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of r){if(!i.isDirectory()||i.isSymbolicLink())return!0;try{let n=await ur(e,i.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function aG(e,t){if(t)return[t];let r;try{r=await Se.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort(ir)}async function oG(e,t){let r=await Vr(e,t);if(r.status!=="current"||!r.state||r.state.archived)return!0;let[i,n,a]=await Promise.all([bn(e,t),Vu(e,t),Ca(e,t)]);return i!==null||n!==null||a!==null}async function sG(e){if(await oG(e.paths,e.name))return[];let t=await Vr(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let r=await ZJ({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(r.pending)return r.findings;let i=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&i.push(c);let n=await eG(e.paths,e.name),a=rG(n,i,e.nowMs);if(a.candidates.length===0)return r.findings;let o=_p(e.paths,e.name);if(!e.repair)return[...r.findings,CN(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await iG(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...r.findings,...s.length>0?[CN(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:pc(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...r.findings,CN(e.name,a,!0,o)]}async function VI(e){if(e.deferAll||await nG(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let r=async n=>{let a=[];for(let o of await aG(e.paths,e.name))try{a.push(...await sG({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:pc(`Native evidence retention refused to clean ${o}: ${s.message}`),path:_p(e.paths,o)})}return a};if(!(e.repair??!1))return r(!1);let i=await r(!1);if(i.some(n=>n.severity==="error")||!i.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return i;try{return await $(e.paths,"prune Native evidence",()=>r(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:pc(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}Qa();Q();Yt();$e();tt();Qa();Q();Yt();oo();Lr();import{createHash as cG,randomUUID as lG}from"crypto";import{promises as ja}from"fs";import Pe from"path";var _N=64*1024*1024,uG=256*1024,GI=16*1024*1024;async function Nt(e){try{return await ja.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dG(e){let t;try{t=await ja.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t){if(!r.isDirectory()||r.isSymbolicLink())continue;let i;try{i=await ur(e,r.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${r.name} has no journal; run doctor before moving`,{cause:n}):n}if(i.status!=="committed"&&i.status!=="rolled-back")throw new Error(`Native transaction ${i.id} is unfinished; recover it before moving`)}}async function fG(e,t){for(let r of await ja.readdir(e.locksDir,{withFileTypes:!0})){let i=Pe.join(e.locksDir,r.name);if(Pe.resolve(i)!==Pe.resolve(t)&&(r.isFile()||r.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${i}`)}}async function hG(e){let t;try{t=await ja.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name))){if(!r.isDirectory()||r.isSymbolicLink())continue;let i=await Dt(e,r.name);if(i){await uh({paths:e,name:r.name,revision:i.capturedRevision,...i.schema==="comet.native.workspace.v3"?{binding:{isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch},...i.finish?{finish:i.finish}:{}}:{}});continue}}}async function pG(e){let t;try{t=await ja.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name)))if(!(!r.isDirectory()||r.isSymbolicLink()))try{let i=await Dt(e,r.name);if(i?.schema==="comet.native.workspace.v3"){let n=await Ai({paths:e,identity:i});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(i){let n=await sa({paths:e,identity:i});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(i){throw new Error(`Native workspace identity for ${r.name} must be aligned and repaired before moving the root`,{cause:i})}}async function zu(e,t){let r=[];async function i(n){let a=await lr({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=Pe.join(n,s.name);if(t.excludedFiles?.has(Pe.resolve(c))){await a.verify();continue}let l=await ja.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())r.push({ref:Pe.relative(e,c).split(Pe.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await Ie({root:e,file:c,maxBytes:_N,label:`Native root file ${Pe.relative(e,c)}`});r.push({ref:Pe.relative(e,c).split(Pe.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await i(e),r.sort((n,a)=>n.ref.localeCompare(a.ref))}async function mG(e,t,r,i){await Pi({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await lr({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=Pe.join(a,l.name);if(Pe.resolve(u)===Pe.resolve(r)){await s.verify();continue}let d=await ja.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=Pe.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Pi({root:i,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Zn({sourceRoot:e,source:u,targetRoot:i,target:f,maxBytes:_N,label:`Native root move file ${Pe.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function mc(e,t,r,i){let n=await zu(e,{rejectSymlinks:!0,excludedFiles:r?new Set([Pe.resolve(r)]):void 0}),a=await zu(t,{rejectSymlinks:!0,excludedFiles:i?new Set([Pe.resolve(i)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function UI(e,t){return Pe.join(e.artifactRoot,`.comet-native-move-${t}`)}function vG(e,t){return Pe.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function gG(e){return`${e}.removing`}function WI(e,t){return Pe.join(Pe.dirname(e),`.${Pe.basename(e)}.${t}.rollback-removing`)}function KI(e,t,r){return Pe.join(Wf(e,t).directory,`root-move-cleanup-${r}.json`)}function wG(e){return JSON.stringify(e,null,2)+`
|
|
305
|
-
`}function yG(e){return cG("sha256").update(e).digest("hex")}function NG(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let r=e,i=Object.keys(r).sort(),n=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||Pe.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function bG(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let i=e;if(JSON.stringify(Object.keys(i).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||i.schema!=="comet.native.root-move-cleanup.v1"||i.transactionId!==t||i.kind!==r||!Array.isArray(i.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=i.entries.map(NG);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=Pe.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:r,entries:n}}async function kG(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=wG(t);if(Buffer.byteLength(r,"utf8")>GI)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await xe(KI(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),yG(r)}async function SG(e){let t=await Ie({root:e.paths.runtimeDir,file:KI(e.paths,e.id,e.cleanup.kind),maxBytes:GI,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return bG(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function AN(e){let t=await zu(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(i=>[i.ref,i]));for(let i of t){let n=r.get(i.ref);if(!n||JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${i.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function zI(e){return e.ref.split("/").length}async function EG(e){let r=[...await AN({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>zI(a)-zI(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=Pe.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await qf({root:e.projectRoot,file:a,maxBytes:_N,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await cg({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),i+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,i)}await AN({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await cg({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function jp(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function YI(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function RG(e,t,r,i){for(let a of[e,t])try{let o=await ur(a,i);if(o.kind!=="root-move")throw new Error(`Transaction ${i} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=Pe.join(r,"runtime","transactions",i,"transaction.json");try{let a=await Ie({root:r,file:n,maxBytes:uG,label:`Staged Native root-move journal ${i}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${i}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${i}`,{cause:a})}}async function JI(e){let t=jp(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Nr(e.projectRoot,t),t}async function Wu(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=jp(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Nr(e.projectRoot,r),r}async function $p(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=r.cleanup;if(i&&i.kind!==e.kind)throw new Error(`Native root move has unfinished ${i.kind} cleanup; cannot start ${e.kind}`);let n=await Nt(e.target),a=await Nt(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!i){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await kG({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await zu(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Wu({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await SG({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await Nt(e.target),a=await Nt(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(i.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await VE({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(i.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Wu({projectRoot:e.projectRoot,config:t,id:e.id})}return await AN({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Wu({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Wu({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await EG({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Wu({projectRoot:e.projectRoot,config:t,id:e.id})}async function XI(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await Nt(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=gG(e.staging);t=await $p({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await zu(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([Pe.resolve(e.lockFile)])}),await mG(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await mc(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await JI({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await Nt(e.destinationPaths.nativeRoot)){if(await Nt(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await mc(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Nt(e.staging))throw new Error("Native move staging tree is missing");await mc(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await ja.rename(e.staging,e.destinationPaths.nativeRoot)}t=await JI({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await Nt(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=vG(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Nt(e.sourcePaths.nativeRoot)&&await mc(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await $p({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:i,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await hG(e.destinationPaths);let n=await ur(e.destinationPaths,e.pending.id);await ws(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Nr(e.projectRoot,o),o}async function QI(e){let t=await X(e.projectRoot)??Ya("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let r=zn(e.toArtifactRoot);if(r===t.native.artifact_root)throw new Error(`Native artifact root is already ${r}`);let i=await pe(e.projectRoot,t.native.artifact_root),n=await pe(e.projectRoot,r);if(q(i.nativeRoot,n.nativeRoot)||q(n.nativeRoot,i.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Nt(i.nativeRoot))throw new Error(`Native source root does not exist: ${i.nativeRoot}`);if(await dG(i),await Nt(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await Ui(i,"root-move",`move root to ${r}`),o=lG(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:r,stage:"copying"},c=YI({id:o,paths:i,now:e.now??new Date}),l=UI(n,o);try{if(await fG(i,a.file),await pG(i),await Nt(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Nr(e.projectRoot,jp(t,s)),await mg(i,c),await e.hooks?.afterRootMoveStage?.("copying",c),await XI({projectRoot:e.projectRoot,config:jp(t,s),pending:s,sourcePaths:i,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:i.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await Ki(a)}}async function ZI(e){let t=await X(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let i=await pe(e.projectRoot,r.fromArtifactRoot),n=await pe(e.projectRoot,r.toArtifactRoot),a=UI(n,r.id),o=await Nt(i.nativeRoot)?i:n,s=await Ui(o,"root-move",`recover root ${r.id}`);try{let c;try{c=await RG(i,n,a,r.id)}catch(v){if(r.stage!=="copying"||!await Nt(i.nativeRoot))throw v;let h=YI({id:r.id,paths:i,now:new Date});await mg(i,h),c={journal:h,paths:i}}if(e.strategy==="continue"){let v=await XI({projectRoot:e.projectRoot,config:t,pending:r,sourcePaths:i,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await Nt(i.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=WI(n.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await Nt(n.nativeRoot)&&await mc(i.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await $p({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-destination",stablePaths:i,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=WI(a,r.id);!t.native.pending_root_move?.cleanup&&await Nt(a)&&await mc(i.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await $p({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-staging",stablePaths:i,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await ur(i,r.id);await zf(i,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:r.fromArtifactRoot}};return await Nr(e.projectRoot,p),{activeNativeRoot:i.nativeRoot,config:p}}finally{await Ki(s)}}oo();Il();Lr();var vc=4096,PG=4096,CG=1024;async function $a(e,t,r){try{let i=await lr({root:F(e,t),directory:t,label:"Native doctor directory",maxEntries:r});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function Hp(e,t){let r=new Map(e.map(i=>[bt.resolve(i.file),{...i,file:bt.resolve(i.file)}]));for(let{paths:i,file:n}of r.values()){let a;try{a=await ul(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Gv(i,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function xG(e,t){let r=Pu(e),i;try{await j(e.projectRoot,r);let n=await Ru(e);if(!n)return[];i=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:r}]}if(i.schema!=="comet.selection.v2"||i.workflow!=="native"||typeof i.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:r}];try{return await Be(e,i.change)?[]:(await De(e,i.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:r}]}return t?(await Op.rm(r,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${i.change}`,path:r}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${i.change}`,path:r}]}async function AG(e){let t=[];for(let r of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await j(F(e,r),r)}catch(i){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${i.message}`,path:r})}return t}async function _G(e,t){let r=[],i=[];for(let n of await $a(e,e.transactionsDir,PG)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await ur(e,n.name)}catch(o){r.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:bt.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){i.push(a),r.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Xa([e],`doctor archive recovery ${a.id}`,async()=>await Hp([{paths:e,file:bt.join(e.locksDir,"root-move.lock")},{paths:e,file:bt.join(e.locksDir,"archive.lock")}],r)?(await Q_({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){i.push(a);continue}r.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){i.push(a),r.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else i.push(a),r.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:r,unfinished:i}}async function IG(e,t,r){let i=[];for(let n of await $a(e,e.locksDir,CG)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=bt.join(e.locksDir,n.name);try{let o=await ul(a);if(o.status==="active")i.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")i.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&r.length===0){let s=await Gv(e,a,o);s.status==="removed"?i.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&i.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else i.push({severity:r.length>0?"error":"warning",code:"lock-stale",message:r.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){i.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return i}async function TG(e,t,r=5){let i=[],n=t?await bN(e,{maxVerifyFailures:r}).then(a=>a.filter(o=>o.name===t)):await bN(e,{maxVerifyFailures:r});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){i.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:bt.join(e.changesDir,a.name,lt)});continue}let o=await Ia(e,a.name,{details:!0,maxVerifyFailures:r});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||i.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:bt.join(e.projectRoot,s.path)}:{}})}return i}async function jG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{let a=await xs(e,n);if(a.status!=="repairable")continue;if(!t.repair){r.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await YR(e,n);o&&r.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){r.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:bt.join(V(e,n),"trajectory.jsonl")})}return r}async function $G(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=await ll(e,n);if(a.status==="missing"){r.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){r.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=Ka(e,n),s=Oe(e,n);if(!t.repair){r.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Xa([e],`migrate Runtime layout for ${n}`,async()=>{let c=await br({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await j(e.runtimeDir,s),await Op.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await br({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Op.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Op.rename(o,s)}),r.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){r.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return r}async function OG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{if(!await Bg(e,n))continue;if(!t.repair){r.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:_s(e,n),repair:"migrate"});continue}let a=await De(e,n);await oP({paths:e,name:n,revision:a.revision})&&r.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:_s(e,n)})}catch(a){r.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:_s(e,n)})}return r}async function HG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=Lu(e,n);try{let o=await Vu(e,n),s=await Vr(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){r.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:bt.join(e.changesDir,n,lt)});continue}if(!t.repair){r.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:bt.join(e.changesDir,n,lt),repair:"migrate"});continue}await OI({paths:e,name:n}),r.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:bt.join(e.changesDir,n,lt)})}catch(o){if(o.code==="ENOENT")continue;r.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return r}async function DG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a;try{a=await bn(e,n)}catch(o){if(o instanceof $u)continue;r.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Mt(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Xa([e],`doctor transition recovery ${n}`,async()=>await Hp([{paths:e,file:bt.join(e.locksDir,"root-move.lock")},{paths:e,file:bt.join(e.locksDir,`transition-${n}.lock`)}],r)?(await f_(e,n),!0):!1))continue;r.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Mt(e,n)})}catch(o){r.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Mt(e,n)})}continue}r.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Mt(e,n),repair:"continue"})}}return r}async function BG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=Pa(e,n),o;try{o=await Ca(e,n)}catch(s){if(s.code==="ENOENT")continue;r.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){r.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Xa([e],`doctor checkpoint recovery ${n}`,async()=>await Hp([{paths:e,file:bt.join(e.locksDir,"root-move.lock")},{paths:e,file:bt.join(e.locksDir,`transition-${n}.lock`)}],r)?(await S_(e,n),!0):!1))continue;r.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){r.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return r}async function Ju(e){let t=e.repair??!1,r=[],i=e.paths,n;try{n=await X(i.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:i.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([pe(i.projectRoot,c.fromArtifactRoot),pe(i.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Hp([{paths:l,file:bt.join(l.locksDir,"root-move.lock")},{paths:u,file:bt.join(u.locksDir,"root-move.lock")}],r))return{healthy:!1,findings:r};let f=await ZI({projectRoot:i.projectRoot,strategy:e.recoveryStrategy});i=await pe(i.projectRoot,f.config.native.artifact_root),a=!1,r.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return r.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:r}}else r.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await AG(i);if(r.push(...o),o.length>0)return{healthy:!1,findings:r};let s=await _G(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return r.push(...s.findings),e.projectOnly||(r.push(...await $G(i,{name:e.name,repair:t})),r.push(...await HG(i,{name:e.name,repair:t})),r.push(...await OG(i,{name:e.name,repair:t})),r.push(...await jG(i,{name:e.name,repair:t})),r.push(...await DG(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),r.push(...await BG(i,{name:e.name,repair:t})),r.push(...await VI({paths:i,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),r.push(...await IG(i,t,s.unfinished)),r.push(...await xG(i,t)),e.projectOnly||r.push(...await TG(i,e.name,n?.native.max_verify_failures??5)),{healthy:r.every(c=>c.severity==="info"),findings:r}}ga();zt();ga();fn();import{promises as rT}from"node:fs";import nT from"node:path";import eT from"node:path";function tT(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Vt(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:tT(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:tT(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>eT.relative(t.projectRoot,eT.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}function aT(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function oT(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function sT(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:FG(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:MG(i,r)}))]:[]]}function cT(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function iT(e,t){let r=ne(e.projectRoot),i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:nT.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function IN(e){let{state:t,paths:r}=e,i=Vt(t),n=e.details?sT(t,null,[]):[],a=oT(e.cursor,t.state_version,0),o=n.slice(a,a+32),s=a+o.length<n.length?aT(t.state_version,0,a+o.length):null;return{schema:"comet.native.status.v2",name:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,archived:!0,archiveRef:nT.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:cT(t),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:i.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:K(t),...e.details?{details:{stateVersion:t.state_version,items:o,nextCursor:s,nextPageArgs:s?["comet","native","status",t.name,"--details","--cursor",s,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function qG(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function Dp(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function FG(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:Dp(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function MG(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Dp(e.summary,t)??""}}async function Yr(e){let t=await zx(e),r=Vt(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await vt({paths:e.paths,state:t.state}),a=await gn({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await ee(e.paths,e.name,{diagnostics:!0}),s=o?{...iT(e.paths,t.state),projectRoot:"."}:iT(e.paths,t.state),c=K(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?qG(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,h=o.children.filter(({status:N})=>N==="active"||N==="verified").length,m=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,g=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,w=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:Dp(N.blocker,u)})),S=o.children.flatMap(({blocker:N})=>{let y=Dp(N,u);return y?[y]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:g,active:w,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:m},risks:S,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":g>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=sT(t.state,o,u),m=oT(e.cursor,t.state.state_version,v),g=h.slice(m,m+32),w=m+g.length<h.length?aT(t.state.state_version,v,m+g.length):null;return{items:g,nextCursor:w,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:cT(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function lT(e){let t;try{t=await rT.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let r=[];for(let i of t)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let n=await rT.readFile(`${ye(e,i.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&r.push(i.name)}catch(n){if(n.code!=="ENOENT")throw n}return r.sort((i,n)=>i.localeCompare(n,"en"))}no();async function Gu(e,t){let r=await vt({paths:e,state:t});return K(t,r)}async function LG(e){let t;try{t=await fT.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort((r,i)=>r.localeCompare(i,"en"))}function VG(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function uT(e,t){let r;try{r=await fT.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let i=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${VG(t)}$`,"u"),n=r.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&i.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:Bp.join(e.archiveDir,n.name)}:null}function WG(e){let t=new Map;for(let r of e){let i=[r.severity,r.code,r.message,r.path??""].join("\0");t.set(i,r)}return[...t.values()]}function Uu(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function dT(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Bp.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function zG(e,t){return t.status==="repairable-legacy-overlay"?{severity:"error",code:"portable-supervisor-overlay-stale",message:t.message,path:t.file,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}:t.status==="incompatible"?{severity:"error",code:"portable-supervisor-overlay-incompatible",message:t.message,path:t.file}:null}async function JG(e,t){let r=[],i=[];for(let n of await qE(e)){let a=io(n);if(t&&a.change!==t)continue;let o=Bp.join(e.transactionsDir,n);try{let s=await yl(e,n);if(!s)continue;r.push(s),i.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){i.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:r,findings:i}}async function TN(e,t){let r=It(e,"--repair"),i=Re(e,"--strategy");if(i!==void 0&&i!=="continue"&&i!=="rollback")throw new B("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();Ce(e);let a=await lI(t),o=await JG(a,n);if(n&&o.findings.length>0){if(i)throw new B("--strategy is only available to the legacy transaction doctor");let d=await Be(a,n)?await Yr({paths:a,name:n,details:!0}):void 0;if(r&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await _u({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Gu(a,v.state)})}let p=await pi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:p.schema,stateVersion:p.state_version},state:p,continuation:await Gu(a,p)})}return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await Be(a,n)){if(i)throw new B("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([uT(a,n),my(a,n)]);if(u){let m=await Yr({paths:a,name:n,details:!0});return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:m,findings:[u],continuation:m.continuation})}if(d&&!r){let m=await Yr({paths:a,name:n,details:!0});return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:m,findings:[dT(a,n)],continuation:m.continuation})}let f=await L(a,n),p=await gn({paths:a,state:f}),v=zG(n,p);if(v&&(p.status==="incompatible"||!r)){let m=await Yr({paths:a,name:n,details:!0});return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:m,findings:[v],continuation:m.continuation})}if(r){if(d){let g=await pi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:g.schema,stateVersion:g.state_version},state:g,continuation:await Gu(a,g)})}let m=await jo({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:m,continuation:await Gu(a,m.state)})}let h=await Yr({paths:a,name:n,details:!0});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:h,continuation:h.continuation})}if(n){if(r){let u=await pi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Gu(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await lT(a),c=o;if(s.length>0||c.findings.length>0){if(i)throw new B("--strategy is only available to the legacy transaction doctor");if(r){let y=await Ju({paths:a,repair:!0,projectOnly:!0}),E=[];for(let k of c.transactions)k.kind==="archive"?await _u({paths:a,name:k.change}):await pi({paths:a,name:k.change}),E.push({kind:k.kind,change:k.change,transactionId:k.journal.id});let P=await TN([],t),b=P.data&&typeof P.data=="object"&&!Array.isArray(P.data)?P.data:{};return{...P,data:{...b,repaired:!0,repairedPortableTransactions:E,repairFindings:y.findings}}}let u=await LG(a),d=new Set(s),f=new Set(c.transactions.filter(y=>y.kind==="migration").map(({change:y})=>y)),p=u.filter(y=>!d.has(y)),[v,h,m,g,w]=await Promise.all([Promise.all(s.map(y=>Yr({paths:a,name:y}))),Promise.all(s.map(y=>uT(a,y))),Promise.all(s.map(y=>my(a,y))),Promise.all(p.map(y=>Ju({paths:a,name:y}))),Ju({paths:a,projectOnly:!0})]),S=WG([...h.filter(y=>y!==null),...s.flatMap((y,E)=>m[E]&&!f.has(y)?[dT(a,y)]:[]),...c.findings,...p.map(y=>({severity:"error",code:"portable-migration-required",message:`Native active change ${y} requires migration to portable Runtime`,path:Bp.join(a.changesDir,y,"comet-state.yaml"),repair:"migrate"})),...g.flatMap(({findings:y})=>y),...w.findings]),N={healthy:S.every(y=>y.severity==="info"),workflow:p.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:p,findings:S};return N.healthy?W("doctor",N):Uu(N)}let l=await Ju({paths:a,...n?{name:n}:{},repair:r,...i?{recoveryStrategy:i}:{}});return l.healthy?W("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}Ig();import{promises as aU}from"fs";import _r from"path";import{readFileSync as GG}from"fs";import hT from"path";var UG=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),KG=new Set(["glob","grep","listfiles","read","readfile","search","view"]),pT=["file_path","filePath","path","target_file","targetFile"],mT=["file_paths","filePaths","paths","files","targets"],vT=["operations","edits"],YG=["patch","diff","patchText","patch_text","changes"];function ON(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function jN(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function XG(e){for(let t of["tool_name","toolName","tool","name"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}return null}function QG(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!hT.isAbsolute(r.trim())))return hT.resolve(r.trim())}}function ZG(e){for(let t of["session_id","sessionId","conversation_id","conversationId"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim().slice(0,256)}}function eU(e){for(let t of["hook_event_name","hookEventName","event_name","eventName"]){let r=e[t];if(typeof r=="string"&&r.trim())return jN(r)}}function tU(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function rU(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function iU(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return rU(e[t]);return e}function $N(e){let t=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let i of r)for(let n of e.matchAll(i)){let a=n[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function Mo(e,t){if(typeof t=="string"){let r=t.trim();r&&e.push(r);return}if(Array.isArray(t)){for(let r of t)Mo(e,r);return}if(ON(t)){for(let r of pT)Mo(e,t[r]);for(let r of mT)Mo(e,t[r]);for(let r of vT)Mo(e,t[r])}}function nU(e,t){let r=[],i=[t,e].filter(ON);for(let n of i){for(let a of pT)Mo(r,n[a]);for(let a of mT)Mo(r,n[a]);for(let a of vT)Mo(r,n[a]);for(let a of YG){let o=n[a];typeof o=="string"&&r.push(...$N(o))}}return typeof t=="string"&&r.push(...$N(t)),[...new Set(r)]}function Ku(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(Sy(e))}catch{let s=$N(e);return s.length>0?{intent:"write",targets:[...new Set(s)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!ON(r))return{intent:"unknown",targets:[],toolName:null};let i=XG(r),n=nU(r,iU(r)),a=QG(r),o=ZG(r);if(eU(r)==="beforeagentstart"){let s=tU(r);return{intent:"context",targets:[],toolName:null,...s?{task:s}:{},...a?{cwd:a}:{},...o?{sessionId:o}:{}}}return i&&UG.has(jN(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i&&KG.has(jN(i))?{intent:"non-write",targets:[],toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i?{intent:"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{},...o?{sessionId:o}:{}}}function gT(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return Ku("",e);try{return Ku(GG(0,"utf8"),e)}catch{return Ku("",e)}}Ee();tt();Q();Tg();function wT(e){let t=`Native change ${e.name} is in ${e.phase}; implementation writes are only allowed in Build.`;return e.phase==="shape"?`${t} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:e.phase==="verify"?`${t} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:e.phase==="archive"?`${t} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${t} Create or select a separate Native change if this write belongs to different work.`}async function oU(e){let{projectRoot:t,paths:r,state:i,request:n}=e,a=ye(r,i.name),o=[],s=[],c=!1,l=!1,u=!1;for(let d of n.targets){let f=_r.resolve(t,d);if(!Oa(t,f)){u=!0;continue}let p=_r.relative(t,f).replaceAll("\\","/");if(p===".comet/config.yaml"){l=!0;continue}if(!Oa(r.nativeRoot,f)){if(await rh(t,f,[_r.join(t,".comet"),r.nativeRoot])){c=!0;continue}s.push(p);continue}if(!Oa(a,f))return{allowed:!1,reason:Oa(r.specsDir,f)?`Published Native specs are updated through Archive. Stage the complete target spec in ${_r.join(a,"specs",_r.relative(r.specsDir,f))}; use comet native spec sync for reference-only corrections, or revise-requirements for requirement changes.`:"Portable Native control state is Runtime-owned",workflow:"native",phase:i.phase,change:i.name};let v=_r.relative(a,f).replaceAll("\\","/");if(v==="brief.md"||v==="children.yaml"||v.startsWith("specs/")){o.push(v);continue}return{allowed:!1,reason:`${v||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:i.phase,change:i.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:i.phase,change:i.name}:o.length>0?i.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await rc({paths:r,name:i.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:i.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:i.phase,change:i.name}:s.length>0?i.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:i.phase,change:i.name}:i.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:i.phase,change:i.name}:i.phase==="verify"||i.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await tc({paths:r,name:i.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:wT(i),workflow:"native",phase:i.phase,change:i.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function Oa(e,t){let r=_r.relative(e,t);return r===""||!r.startsWith("..")&&!_r.isAbsolute(r)}function sU(e,t,r){return r.targets.length>0&&r.targets.every(i=>{let n=_r.resolve(e,i);return Oa(e,n)?_r.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||Oa(t,n):!0})}async function cU(e){let t=await X(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let r=await pe(e,t.native.artifact_root),i;try{i=await aU.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let n=[];for(let a of i.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await Be(r,a.name)){let o=await L(r,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await De(r,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:r,changes:n}}var lU=th("nativeActiveContext",e=>cU(e));async function yT(){let{intent:e,targets:t}=await gT();return{intent:e,targets:t}}async function NT(e,t,r){let i=await lU(e);if(!i)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.changes.length===0)return{allowed:!0,reason:sU(e,i.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let n;if(r){if(n=i.changes.find(l=>l.state.name===r),!n)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(i.changes.length===1)n=i.changes[0];else{let l=await Qx(i.paths);if(n=i.changes.find(u=>u.state.name===l),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return oU({projectRoot:e,paths:i.paths,state:n.state,request:t});let o=!1,s=!1,c=!1;for(let l of t.targets){let u=_r.resolve(e,l);if(!Oa(e,u)){s=!0;continue}if(_r.relative(e,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(Oa(i.paths.nativeRoot,u)){o=!0;continue}if(await rh(e,u,[_r.join(e,".comet"),i.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:wT(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function bT(e,t){let r=Re(e,"--hook-output");if(r!==void 0&&r!=="copilot")throw new B("--hook-output must be copilot");Ce(e);let i=await NT(t,await yT());return r==="copilot"?{command:"hook-guard",exitCode:0,data:i,text:i.allowed?`{}
|
|
296
|
+
`);c&&(m=await Vx({paths:l.paths,name:r,finish:c}));let y=await fy({paths:l.paths,name:r}),E="capabilities are also declared by:",P=y.blockers.filter(oe=>!oe.startsWith(E)),b=[],k=m.workspace.isolation!=="current"&&m.workspace.finish===null;if(k&&P.push("Native branch and worktree isolation require a workspace finish choice"),!k)try{await tp({paths:l.paths,state:m,appliedSpecChanges:f,pullRequestFinish:l.config.native.finish?.pull_request})}catch(oe){let ce=oe.message;P.push(ce),b.push({message:ce,paths:oe instanceof wn?oe.paths:[],workspaceRoot:oe instanceof wn?oe.workspaceRoot:l.paths.projectRoot})}let R=y.capabilityPeers.length>0&&s!==r,I=R&&P.length===0?U(m,null,{archiveMode:"preview"}):null,C=I?{...I,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],requiresUserDecision:!0,userCommunication:{required:!0,message:m.language==="zh-CN"?`当前规格也由 ${y.capabilityPeers.join(", ")} 修改。是否先归档 ${r}?其他 change 随后需要对齐最新规格。`:`The same specifications are changed by ${y.capabilityPeers.join(", ")}. Archive ${r} first? The other changes must then align with the latest specifications.`,suggestedReply:m.language==="zh-CN"?`先归档 ${r}`:`Archive ${r} first`,agentInstruction:"Wait for the ordering decision, then execute the matching dry-run commandAlternative."},commandAlternatives:[{name:"archive-this-change-first",commandArgs:["comet","native","archive",r,"--dry-run","--serial-first",r],description:`Archive ${r} before ${y.capabilityPeers.join(", ")}`,inputOptions:[],requiredInputs:[]}],runnerAction:{...I.runnerAction,kind:"none"}}:k?U(m):U(m,null,{archiveMode:"preview",archiveBlockers:P}),Ne=[...P,...R?[`${E} ${y.capabilityPeers.join(", ")}`]:[]];return W("archive --dry-run",{...y,ready:Ne.length===0,blockers:Ne,...b.length>0?{workspaceFinishBlockers:b}:{},workspaceFinish:m.workspace.finish,continuation:s===r&&C.commandArgs?{...C,commandArgs:[...C.commandArgs,"--serial-first",r]}:C},`Native Archive preview: ${Ne.length===0?"ready":"blocked"}
|
|
297
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new H("archive requires --confirmed when native.archive_confirmation is required");if(m&&m.workspace.isolation!=="current"&&m.workspace.finish===null){let y=U(m);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:y},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let g=null;if(m)try{g=await tp({paths:l.paths,state:m,appliedSpecChanges:f,pullRequestFinish:l.config.native.finish?.pull_request})}catch(y){let E=y.message,P=y instanceof wn?y.paths:[],b=y instanceof wn?y.workspaceRoot:l.paths.projectRoot,k={action:m.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:b,cleanup:{performed:!1,reason:null},blockedPaths:P,message:E,recoveryArgs:["git","-C",b,"status","--short"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:m,workspaceFinish:m.workspace.finish,workspaceFinishResult:k,continuation:U(m,null,{archiveMode:"blocked",archiveBlockers:[E]})},error:{code:"conflict",message:E}}}let w;try{w=await _u({paths:l.paths,name:r,...s?{serialFirstChange:s}:{}})}catch(y){if(!(y instanceof Au)||!m)throw y;let E=await fy({paths:l.paths,name:r}),P=y.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...E,workspaceFinish:m.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:y.message,commandArgs:P,inputOptions:y.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:y.message}}}m=w.state,!g&&m&&(g=await tp({paths:l.paths,state:m,archiveDir:w.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request}));let S=null;if(g)try{S=await RA({paths:l.paths,state:w.state,name:r,archiveDir:w.archiveDir,transactionId:w.transactionId,plan:g})}catch(y){if(!(y instanceof Iu))throw y;return{command:"archive",exitCode:73,data:{...w,workspaceFinish:w.state.workspace.finish,workspaceFinishResult:y.result,continuation:{disposition:"blocked",reason:y.message,commandArgs:y.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:y.message}}}let N=S?.merged===!0?await xx({childPaths:l.paths,childState:w.state}):null;return W("archive",{...w,artifactRefs:["brief.md",...w.state.verification_report?[w.state.verification_report]:[]].map(y=>fI.relative(t,fI.join(w.archiveDir,y)).replaceAll("\\","/")),workspaceFinish:w.state.workspace.finish,workspaceFinishResult:S,...N?{parentAdvance:N.parentAdvance}:{},...N?.parentState?{parentState:N.parentState}:{},continuation:U(N?.parentState??w.state)},`Archived Native change ${r} to ${w.archiveDir}
|
|
298
|
+
`)}if(s)throw new H("--serial-first is only valid for portable Native changes");if(!i&&c)throw new H("--finish is only valid with --dry-run");if(Ce(e),i)return{command:"archive --dry-run",exitCode:65,data:{change:r,migrationRequired:!0,repairCommand:`comet native doctor ${r} --repair`},error:{code:"invalid-data",message:`Native active change ${r} must migrate before Archive preview`}};let v=await mi({paths:l.paths,name:r});return W("archive",{migration:{from:"legacy",to:v.schema,completed:!0},state:v,continuation:U(v)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
|
|
299
|
+
`)}Ee();Ee();Ws();import{createHash as Yz}from"node:crypto";import{constants as vN,promises as wi}from"node:fs";import Bo from"node:path";import{TextDecoder as Xz}from"node:util";zr();Ir();Q();na();sn();Ws();var pI={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},Ze=class extends Error{constructor(r,i){super(i);this.kind=r}kind};function Qz(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function mI(e){let t=Qz(e.scope.baseline),[r,i]=await Promise.all([kn({changeDir:se(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),Es(e.paths,t,{origin:"explicit"})]),n=Fs({baseline:t,current:i,contractHash:e.scope.authority.contractHash,declaredArtifacts:e.scope.authority.declaredArtifacts,noCodeReason:e.scope.authority.noCodeReason,...e.scope.authority.gitChangedPaths?{gitChangedPaths:e.scope.authority.gitChangedPaths}:{},...e.scope.authority.externalDrift?{externalDrift:e.scope.authority.externalDrift}:{}});return{contractHash:r.contract.contractHash,snapshotHash:n.scope.currentProjectionHash}}function vI(e,t){let r=(e??(()=>new Date))();if(!(r instanceof Date)||!Number.isFinite(r.getTime()))throw new Error(`Native check ${t} time is invalid`);return r.toISOString()}function Zz(e,t,r){let i=[],n=r.scope.contractHash,a=r.scope.currentProjectionHash;return e.contractHash!==n&&i.push("contract-before-does-not-match-scope"),e.snapshotHash!==a&&i.push("implementation-before-does-not-match-scope"),t.contractHash!==e.contractHash&&i.push("contract-changed-during-check"),t.snapshotHash!==e.snapshotHash&&i.push("implementation-changed-during-check"),t.contractHash===e.contractHash&&t.contractHash!==n&&i.push("contract-after-does-not-match-scope"),t.snapshotHash===e.snapshotHash&&t.snapshotHash!==a&&i.push("implementation-after-does-not-match-scope"),i}function eJ(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function kp(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function tJ(e,t){let r=Bo.resolve(e),i=Bo.resolve(t);if(!q(r,i))throw new Ze("unsafe-file","Scoped file parent escapes the project root");let n=[],a=r;for(let o of["",...Bo.relative(r,i).split(Bo.sep).filter(Boolean)]){o&&(a=Bo.join(a,o));let s;try{s=await wi.lstat(a)}catch(l){throw l.code==="ENOENT"?new Ze("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new Ze("unsafe-file","Scoped file parent is not a real directory");let c=await wi.realpath(a);if(n.length>0&&!q(n[0].realPath,c))throw new Ze("unsafe-file","Scoped file parent resolves outside the project");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs,ctimeMs:s.ctimeMs})}return{physicalRoot:n[0].realPath,chain:n}}async function gI(e){for(let t of e){let r;try{r=await wi.lstat(t.path)}catch(i){throw i.code==="ENOENT"?new Ze("unsafe-file","Scoped file parent changed while reading"):i}if(!r.isDirectory()||r.isSymbolicLink()||!eJ(t,r)||await wi.realpath(t.path)!==t.realPath)throw new Ze("unsafe-file","Scoped file parent changed while reading")}}async function rJ(e){let t=Bo.resolve(e.projectRoot,...e.file.path.split("/"));if(!q(e.projectRoot,t))throw new Ze("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:r,chain:i}=await tJ(e.projectRoot,Bo.dirname(t)),n;try{n=await wi.lstat(t)}catch(c){throw c.code==="ENOENT"?new Ze("scope-mismatch","Scoped file no longer exists"):c}if(!n.isFile()||n.isSymbolicLink())throw new Ze("unsafe-file","Scoped file is not a real regular file");if(n.size!==e.file.expected.size)throw new Ze("scope-mismatch","Scoped file size no longer matches its projection");let a=await wi.realpath(t);if(!q(r,a))throw new Ze("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":vN.O_RDONLY|vN.O_NOFOLLOW|vN.O_NONBLOCK,s=await wi.open(t,o).catch(c=>{throw c.code==="ENOENT"?new Ze("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new Ze("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),wi.lstat(t),wi.realpath(t)]);if(await gI(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!kp(n,c)||!kp(c,l))throw new Ze("unsafe-file","Scoped file changed while opening");let d=[],f=Yz("sha256"),p=Buffer.allocUnsafe(64*1024),v=0;for(;;){let S=e.file.expected.size+1-v;if(S<1)throw new Ze("scope-mismatch","Scoped file exceeds its projected size");let N=await s.read(p,0,Math.min(p.length,S),null);if(N.bytesRead===0)break;if(v+=N.bytesRead,v>e.file.expected.size)throw new Ze("scope-mismatch","Scoped file exceeds its projected size");let y=Buffer.from(p.subarray(0,N.bytesRead));d.push(y),f.update(y)}let[h,m,g]=await Promise.all([s.stat(),wi.lstat(t),wi.realpath(t)]);if(await gI(i),v!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new Ze("scope-mismatch","Scoped file content no longer matches its projection");if(!h.isFile()||!m.isFile()||m.isSymbolicLink()||g!==a||!q(r,g)||!kp(c,h)||!kp(c,m))throw new Ze("unsafe-file","Scoped file changed while reading");let w=Buffer.concat(d,v);if(w.includes(0))return{bytes:v,text:null};try{return{bytes:v,text:new Xz("utf-8",{fatal:!0}).decode(w)}}catch{return{bytes:v,text:null}}}finally{await s.close()}}function iJ(e,t){let r=new Map(e.current.entries.map(l=>[l.path,l])),i=[],n=[],a=[],o=new Set(e.authority.externalDrift?.paths??[]),s=new Map(e.scope.unresolvedScopes.filter(l=>l.kind==="unattributed-change"&&l.path!==null).map(l=>[l.path,l.id])),c=e.scope.unresolvedScopes.some(l=>l.kind==="scope-detail-overflow"&&t.has(l.id));for(let l of bo({baseline:e.baseline,current:e.current,declaredArtifacts:e.scope.declaredArtifacts})){if(o.has(l.path))continue;if(l.attributedTo.length===0){let d=s.get(l.path);if(d===void 0?c:t.has(d))continue;a.push(l.path);continue}if(!l.after)continue;let u=r.get(l.path);if(!u||u.hash!==l.after.hash||u.size!==l.after.size||u.type!=="file"){n.push(l.path);continue}i.push({path:l.path,expected:l.after})}return i.sort((l,u)=>l.path.localeCompare(u.path,"en")),n.sort((l,u)=>l.localeCompare(u,"en")),a.sort((l,u)=>l.localeCompare(u,"en")),{files:i,mismatches:n,unowned:a}}function nJ(e,t,r){let i=t.split(`
|
|
300
|
+
`);for(let n=0;n<i.length;n+=1){let a=i[n].endsWith("\r")?i[n].slice(0,-1):i[n],o=n+1;/^(?:<{7}|={7}|>{7})(?: |$)/u.test(a)&&r({path:e,line:o,kind:"conflict-marker"}),/[ \t]+$/u.test(a)&&r({path:e,line:o,kind:"trailing-whitespace"}),/^ +\t/u.test(a)&&r({path:e,line:o,kind:"space-before-tab"})}}async function aJ(e){if(e.state.partial_allowance===null)return new Set;let t=await du(e.paths,e.state.name,e.state.partial_allowance),r=e.scope.scope.unresolvedScopes.map(i=>i.id).sort();if(t.change!==e.state.name||t.scopeHash!==e.scope.scope.scopeHash||JSON.stringify(t.scopeIds)!==JSON.stringify(r))throw new Error("Native partial allowance does not match the current implementation scope");return new Set(t.scopeIds)}async function wI(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await fn(e.paths,e.state.name,e.state.implementation_scope),r=await mI({paths:e.paths,state:e.state,scope:t}),i=vI(e.clock,"start"),n=await aJ({paths:e.paths,state:e.state,scope:t}),a=iJ(t,n),o=[],s=0,c=b=>(s+=1,o.length>=je.maxIssues?!1:(o.push(b),!0)),l=[],u={files:[],diagnostics:[]},d=0,f=()=>{u.files.length>0&&l.push(u),u={files:[],diagnostics:[]},d=0};for(let b of a.files)(b.expected.size>je.maxFileBytes||u.files.length>0&&(u.files.length>=je.maxFiles||d+b.expected.size>je.maxTotalBytes))&&f(),u.files.push(b),d+=b.expected.size,b.expected.size>je.maxFileBytes&&f();f();let p=[...a.unowned,...a.mismatches].sort((b,k)=>b.localeCompare(k,"en")).map(b=>({path:b,line:1,kind:"scope-mismatch"}));for(let b=0;b<p.length;b+=je.maxFiles)l.push({files:[],diagnostics:p.slice(b,b+je.maxFiles)});let v=l.reduce((b,k)=>b+k.files.length+k.diagnostics.length,0),h=0,m=0,g=0,w=[];for(let b of l){let k={filesSelected:b.files.length+b.diagnostics.length,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0},R=I=>{k.issueCount+=1,c(I)&&(k.recordedIssueCount+=1)};for(let I of b.diagnostics)R(I);for(let I of b.files){if(I.expected.size>je.maxFileBytes){R({path:I.path,line:1,kind:"scan-limit"});continue}try{let C=await rJ({projectRoot:e.paths.projectRoot,file:I});g+=C.bytes,k.bytesScanned+=C.bytes,C.text===null?(m+=1,k.binaryFilesSkipped+=1,R({path:I.path,line:1,kind:"binary-skipped"})):(h+=1,k.filesScanned+=1,nJ(I.path,C.text,R))}catch(C){if(!(C instanceof Ze))throw C;R({path:I.path,line:1,kind:C.kind})}}w.push(k)}let S=await mI({paths:e.paths,state:e.state,scope:t}),N=vI(e.clock,"end"),y=Zz(r,S,t);o.sort((b,k)=>b.path.localeCompare(k.path,"en")||b.line-k.line||pI[b.kind]-pI[k.kind]);let E=SC({change:e.state.name,sourceRevision:e.state.revision,status:s===0&&y.length===0?"passed":"failed",startedAt:i,endedAt:N,contract:{expectedHash:t.scope.contractHash,beforeHash:r.contractHash,afterHash:S.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:r.snapshotHash,afterSnapshotHash:S.snapshotHash},counts:{filesSelected:v,filesScanned:h,binaryFilesSkipped:m,bytesScanned:g,issueCount:s,recordedIssueCount:o.length,...w.length>1?{batches:w}:{}},issues:o,issuesTruncated:s>o.length,stale:y.length>0,staleReasons:y}),P=await C_({paths:e.paths,name:e.state.name,receipt:E});return{receipt:un(E),ref:P}}it();async function yI(e){return $(e.paths,`check ${e.name}`,()=>Mi(e.paths,e.name,`check ${e.name}`,()=>oJ(e)))}async function oJ(e){await Hu(e.paths,e.name);let t=await Be(e.paths,e.name);if(t.phase!=="verify")throw new Error(`Native check requires Verify, got ${t.phase}`);if(!t.implementation_scope)throw new Error("Native check requires an implementation scope");let r=await __({paths:e.paths,state:t});if(r)return{change:t,receipt:r.checkReceipt,checkRef:r.checkReceiptRef,ref:r.ref};let i=await wI({paths:e.paths,state:t}),n=await A_({paths:e.paths,state:t,checkReceipt:i.receipt,checkReceiptRef:i.ref});return{change:t,receipt:i.receipt,checkRef:i.ref,ref:n.ref}}async function NI(e,t){let r=Qe(e,"change name");Ce(e);let{paths:i}=await xr(t);if(await _e(i,r))throw new H(`comet native check is a legacy-only command. Run comet native status ${r} --json and follow its continuation to dispatch verification through comet native next.`);let n=await yI({paths:i,name:r}),a={ref:n.ref,hash:n.receipt.receiptHash,status:n.receipt.status,checker:n.receipt.checker,counts:n.receipt.counts,issues:n.receipt.issues,issuesTruncated:n.receipt.issuesTruncated,stale:n.receipt.stale,staleReasons:n.receipt.staleReasons,startedAt:n.receipt.startedAt,endedAt:n.receipt.endedAt,sourceRevision:n.receipt.sourceRevision},o=n.receipt.status==="passed"&&!n.receipt.stale;return{command:"check",exitCode:o?0:1,data:a,text:`Native check ${o?"passed":"failed"}: ${n.ref}
|
|
301
|
+
`}}import{promises as fT}from"node:fs";import Bp from"node:path";import{promises as Op}from"fs";import bt from"path";Ee();tt();import{promises as bJ}from"fs";pl();ct();Ee();Ps();Q();en();Il();async function bI(e,t){let r=[],i=V(e,t.name),n=Jn(i,kr.stateRef),a;try{a=await pt(i)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&r.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Jn(i,a.trajectoryRef),s=await xs(e,t.name);if(s.status==="repairable")return r.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await Zt(i,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Jn(i,a.checkpointRef);try{let u=await Cs(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}na();Lr();var sJ=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function cJ(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function lJ(e){return e?e.map(cJ).join(" "):null}function uJ(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function Kr(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function dJ(e){return e.map(t=>Kr(t,[],null))}function fJ(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[Kr("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(Kr("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(Kr("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Kr("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(Kr("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(Kr("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Kr("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Lt(e,t){let r=t.commandArgs===void 0?uJ(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?lJ(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??dJ(t.requiredInputs??[])}}function Sp(e){let r=(e.findings??[]).filter(d=>!As(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||sJ.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return Lt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Lt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Kr("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Lt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Lt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Lt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Lt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Kr("summary",["--summary"],"<summary>")]});if(n)return Lt(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Lt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Kr("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Lt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Lt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Lt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Lt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Lt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Kr("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Lt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Lt(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=fJ(e.state);return Lt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}Ee();Q();Lr();import Mu from"path";var kI=8,hJ={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function pJ(e){let t=hJ[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:As(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function mJ(e,t,r){if(!r.path)return null;let i;if(Mu.isAbsolute(r.path)?i=Mu.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Mu.resolve(se(e,t.name),...r.path.split(/[\\/]/u)):i=Mu.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=Mu.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function vJ(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function gN(e){return e.findings.map(t=>{let r=pJ(t.code);return{code:t.code,message:t.message,severity:r.severity,path:mJ(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:vJ(r.retry,e.state,t.code),repairCommand:r.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function wN(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,kI),truncated:t.length>kI}}var SI=240,EI=8,Ep=50;function RI(e){let t=Array.from(e);return t.length<=SI?e:`${t.slice(0,SI-1).join("")}…`}function gJ(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function wJ(e){let t=[...new Set(e.map(gJ))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,EI),reasonCount:e.length,codesTruncated:t.length>EI};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Ep),reasonsTruncated:e.length>Ep}}}async function PI(e){let t=null;try{let s=await Ca(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Pa(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Pa(e.paths,e.state.name)}}let r=await k_({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=wJ(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ra.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:RI(r.checkpoint.summary),nextAction:RI(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Ra.maxArtifacts}}Q();zr();en();Js();sn();async function yJ(e,t){let r=V(e,t.name),i=await pt(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Cs(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await Zt(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function NJ(e,t){let r=await yJ(e,t);return{committed:r,latest:QA(r),history:XA(r)}}async function CI(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await NJ(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}zr();Lr();Yt();Q();var kJ=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ar=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function yN(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function SJ(e){return(await Ru(e))?.change??null}function EJ(e,t,r=!1,i){return Sp({state:e,archiveReady:t,evidenceRetreat:r}).command}async function RJ(e,t){let r=se(e,t.name),i=[...(await Wg(r,t.brief)).findings,...(await EP(e,t)).findings,...await bI(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Rs(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Qf(e,n);a.complete||i.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await kn({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await bn(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await zg(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function Ia(e,t,r){let i=await SJ(e)===t,n=await ll(e,t),a=await $l(e,t),o;try{let k=await Vr(e,t);if(k.status==="migration-required"&&k.state)return{name:t,phase:k.state.phase,revision:"revision"in k.state?k.state.revision:null,approval:k.state.approval,verificationResult:k.state.verification_result,specChanges:k.state.spec_changes.length,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:k.schema,migrationRequired:!0,minimumRuntimeVersion:k.minimumRuntimeVersion,error:k.message};if(k.status!=="current"||!k.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:k.schema,minimumRuntimeVersion:k.minimumRuntimeVersion,error:k.message??`Native change ${t} is incompatible`};o=k.state}catch(k){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:k.message}}if(n.status!=="available"){let k={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},R=gN({paths:e,state:o,findings:[k]}),I=Sp({state:o,findings:R});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:I.command,archiveReady:!1,inspection:{freshness:"stale",codes:[k.code],reasonCount:1,codesTruncated:!1},findingSummary:wN(R),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:I,workspace:a,runtime:n,...r?.details?{findings:R}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:k.message}:{}}}let s=await PI({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await CI(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let k=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:k,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let k=await kn({changeDir:se(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),R=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Ne=await Ro(e,o.name,o.verification_evidence);for(let oe of Ne.acceptanceTrace.entries)R.set(oe.acceptanceId,oe.status==="failed"?"failed":oe.status==="missing"?"missing":"satisfied")}let I=EE({criteria:k.contract.acceptance,acceptanceHash:k.contract.acceptanceHash,verificationStatuses:R,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),C=I.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",I.nextCursor,"--project-root",e.projectRoot]:null;u={...I,...C?{nextPageCommand:yN(C),nextPageArgs:C}:{}}}catch(k){if(r.acceptanceCursor)throw k;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let k=await ip(e,o.name,{tolerateInvalidSiblings:!0});d.push(...k.findingCodes.map(R=>({code:R,message:`Native change overlap is visible in the current root: ${R}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let k=await Dt(e,o.name);if(k)if(k.schema==="comet.native.workspace.v3"){let R=await _i({paths:e,identity:k});R.state==="drifted"&&R.code&&f.push({code:R.code,message:R.message??"Native workspace binding is no longer valid"})}else{let R=await sa({paths:e,identity:k});f.push(...R.findingCodes.map(I=>({code:I,message:`Native workspace advisory changed: ${I} (${R.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],v=!1;if(o.phase==="verify"){let k=await j_({paths:e,state:o});v=k.freshness!=="fresh",p.push(...k.findingCodes.map(R=>({code:R,message:`Native Verify implementation scope is not current: ${R}`})))}let h=null,m=[];if(o.phase==="archive")try{h=await mp({paths:e,name:o.name}),m.push(...h.findingCodes.map(k=>({code:k,message:`Native Archive is blocked: ${k}`})))}catch{m.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await RJ(e,o),...s.findings,...d,...f,...p,...l,...m].filter((k,R,I)=>I.findIndex(C=>C.code===k.code&&C.path===k.path)===R),w=gN({paths:e,state:o,findings:g}),S=w.filter(k=>!As(k.code)),N=o.phase==="archive"&&h?.ready===!0&&S.length===0,y=v||o.phase==="archive"&&(h?.findingCodes??[]).some(k=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(k)),E=w.some(k=>k.code==="trajectory-tail-incomplete"||k.code==="trajectory-invalid"||k.requiredAction==="return-to-bound-working-directory"||k.requiredAction==="repair-workspace-binding"),P=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",b=w.find(k=>k.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:E||P?null:EJ(o,N,y,r?.clarificationMode),archiveReady:N,inspection:s.inspection,findingSummary:wN(w),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Sp({state:o,findings:w,archiveReady:N,evidenceRetreat:y,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:w.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Ep,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:w.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...b?{error:b.message}:{}}}async function NN(e){let t;try{t=await br({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await bJ.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Ar.maxChanges))throw new Error(`Native status exceeds ${Ar.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}function Rp(e,t){let r=t.toString(36),i=B("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${r}.${i}`}function PJ(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=kJ.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let i=B("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:r});if(t[3]!==i)throw new Error("Native status cursor integrity check failed");return r}async function CJ(e,t){let r=await NN(e),i=B("comet.native.status-names.v1",r),n=PJ({namesHash:i,total:r.length,cursor:t?.cursor}),a=await Promise.all(r.slice(n,n+Ar.maxItems).map(u=>Ia(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,p={schema:"comet.native.status-page.v1",total:r.length,offset:n,items:d,nextCursor:f<r.length?Rp(i,f):null,nextPageCommand:f<r.length?yN(["comet","native","status","--cursor",Rp(i,f)]):null,nextPageArgs:f<r.length?["comet","native","status","--cursor",Rp(i,f)]:null,limits:{...Ar}};if(Buffer.byteLength(JSON.stringify(p),"utf8")>Ar.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<r.length?Rp(i,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:r.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?yN(l):null,nextPageArgs:l,limits:{...Ar}}}async function bN(e,t){return(await CJ(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}Ws();Ee();import{createHash as JJ,randomUUID as GJ}from"node:crypto";import{constants as PN,promises as Se}from"node:fs";import qe from"node:path";tt();zr();it();Q();var xp=Ha(Mn(),1);Oe();Ee();qr();it();Q();Yt();import{randomUUID as xJ}from"crypto";import{promises as TI}from"fs";import SN from"path";import{isDeepStrictEqual as EN}from"util";en();na();wl();var qo=/^[a-f0-9]{64}$/u,AJ=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),_J=new Set(["sourceHash","targetHash","nextJournal"]),IJ=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),xI=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),TJ=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Pp(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function AI(e){return JSON.stringify(e,null,2)+`
|
|
302
|
+
`}function RN(e){return e.schema===Xe?fh(e):lo(e)}function kN(e,t){return{...e,schema:Xe,minimum_runtime_version:2,revision:t}}function jJ(e){return{...e,schema:Qi,minimum_runtime_version:2,revision:1,previousState:kN(e.previousState,1),nextState:kN(e.nextState,2)}}function Cp(e,t){let r=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ye,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(r&&t?.incrementRetreatRevision?1:0),phase:r?"build":e.phase,verification_result:r?"pending":e.verification_result,verification_report:r?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:r?!1:e.archived}}function $J(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,r=t?G(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:Un,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:r,previousState:Cp(e.previousState),nextState:{...Cp(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:r},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:qi.definition.metadata.version,skillHash:ju}:e.nextRun}}function _I(e,t){return JSON.stringify(e)===JSON.stringify(t)}function fc(e,t){return JSON.stringify(fh(e))===JSON.stringify(fh(t))}function II(e,t){return JSON.stringify(lo(e))===JSON.stringify(lo(t))}function En(e,t){return EN(e,t)}function OJ(e,t,r,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Pp(n,IJ,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!qo.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!qo.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=oa(n.previousRun),o=oa(n.nextRun);if(a.runId!==o.runId||r.run_id!==o.runId||r.phase!=="build"&&r.phase!=="verify"||o.currentStep!==r.phase||o.pending!==null||o.status!=="running"||r.verification_result!=="pending"||r.verification_report!==null||r.implementation_scope!==null||r.verification_evidence!==null||r.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&r.phase==="build"||a.currentStep==="archive"&&r.phase==="build",c=a.currentStep===r.phase?a:s?{...a,currentStep:r.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!En(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==xI.size||u.some(f=>!xI.has(f))||l.fromSchema!==Xe||l.toSchema!==Ye||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==r.phase||l.reason!==(r.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(r.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=G(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:i,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:r.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function Lu(e,t){return SN.join(V(e,t),"schema-migration.json")}function HJ(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Pp(e,AJ,"Native schema migration journal");let r=e;if(r.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(r.change!==t)throw new Error("Schema migration change mismatch");let i=r.fromSchema===Kt&&r.toSchema===Xe,n=r.fromSchema===Xe&&r.toSchema===Ye;if(!i&&!n)throw new Error("Schema migration route is unsupported");if(typeof r.id!="string"||r.id.length===0)throw new Error("Schema migration id is invalid");if(typeof r.sourceHash!="string"||!qo.test(r.sourceHash)||typeof r.targetHash!="string"||!qo.test(r.targetHash))throw new Error("Schema migration hash is invalid");if(typeof r.createdAt!="string"||Number.isNaN(Date.parse(r.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=i?Pi(r.nextState):cr(r.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(G((0,xp.stringify)(RN(a)))!==r.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(r.transition!==void 0){if(!r.transition||typeof r.transition!="object")throw new Error("Schema migration transition target is invalid");Pp(r.transition,_J,"Schema migration transition target");let l=r.transition;if(typeof l.sourceHash!="string"||!qo.test(l.sourceHash)||typeof l.targetHash!="string"||!qo.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=i?Ly(l.nextJournal,t):My(l.nextJournal,t);if(G(JSON.stringify(l.nextJournal,null,2)+`
|
|
303
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(i&&a.schema===Xe?fc(a,u.previousState)||fc(a,u.nextState):a.schema===Ye&&(II(a,u.previousState)||II(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(i&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(r.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ye)throw new Error("Schema migration transition supersede target schema is invalid");s=OJ(r.transitionSupersede,t,a,r.id)}let c;if(r.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!r.runRetreat||typeof r.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Pp(r.runRetreat,TJ,"Schema migration Run retreat");let l=r.runRetreat,u,d;try{u=oa(l.previousRun),d=oa(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!qo.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ye||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:r.id,change:t,fromSchema:r.fromSchema,toSchema:r.toSchema,sourceHash:r.sourceHash,targetHash:r.targetHash,createdAt:r.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Vu(e,t){let r=Lu(e,t),i=F(e,r);await j(i,r);try{let n=await Bf({root:i,file:r,maxBytes:524288,label:"Native schema migration journal"});return HJ(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function DJ(e,t,r){let i=await Rs(e,t),n=i?await Qf(e,i):await Zf(e,{now:new Date(r),origin:"legacy-migration"});if(!n.complete){let a=Rg(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new Ts(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}i===null&&await Cg(e,t,n)}async function jI(e){try{return await Br(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function BJ(e,t){let r=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:r.nextRun.runId,data:{...r.eventData,migrationId:e.id,evidenceHash:r.evidenceHash}}}async function $I(e,t){let r=t.transitionSupersede,i=V(e,t.change),n=await Zt(i,r.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!EN(o.event,BJ(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function qJ(e,t,r){if(!t.transitionSupersede)return;let i=Mt(e,t.change),n=await jI(i);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=V(e,t.change),o=await pt(a),s=await $I(e,t),c=await Cs(a,t.transitionSupersede.nextRun.checkpointRef);if(!r||!o||!En(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==G(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function FJ(e,t,r){let i=t.transitionSupersede;if(!i)return;let n=V(e,t.change),a=await pt(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!En(a,i.nextRun)){if(!En(a,i.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await co(n,i.nextRun),await r?.afterRunStateWritten?.(t)}if(!En(await pt(n),i.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await $I(e,t);if(o.sequence===null){let l=await Sa({changeDir:n,run:i.nextRun,type:"state_migrated",data:{...i.eventData,migrationId:t.id,evidenceHash:i.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await r?.afterTrajectoryWritten?.(t),await Oo({changeDir:n,run:i.nextRun,trajectoryOffset:o.sequence,evidenceHash:i.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t);let s=Mt(e,t.change),c=await jI(s);if(c!==null){if(c!==i.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await TI.rm(s),await r?.afterTransitionSuperseded?.(t)}}async function MJ(e,t,r){if(!t.runRetreat)return;let i=V(e,t.change),n=await pt(i);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!En(n,t.runRetreat.nextRun)){if(!En(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await co(i,t.runRetreat.nextRun),await r?.afterRunStateWritten?.(t)}let a=await Zt(i,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Sa({changeDir:i,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await r?.afterTrajectoryWritten?.(t),await Oo({changeDir:i,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t)}async function LJ(e,t,r){let i=await Vu(e,t);if(!i)return null;if(await $s(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=SN.join(se(e,t),lt),a=await Br(n);if(await qJ(e,i,a===i.targetHash),await DJ(e,t,i.createdAt),a!==i.targetHash){if(a!==i.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${i.sourceHash}, actual ${a}`);await xe(n,(0,xp.stringify)(RN(i.nextState))),await r?.afterStateWritten?.(i)}if(i.transition){let o=Mt(e,t),s=await Br(o);if(s!==i.transition.targetHash){if(s!==i.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${i.transition.sourceHash}, actual ${s}`);await fe(o,i.transition.nextJournal),await r?.afterTransitionWritten?.(i)}}return await FJ(e,i,r),await MJ(e,i,r),await TI.rm(Lu(e,t),{force:!0}),i.nextState}async function VJ(e){let t=V(e.paths,e.state.name),r=await pt(t);if(!r||r.runId!==e.state.run_id||r.currentStep!==e.state.phase||r.currentStep!=="verify"&&r.currentStep!=="archive"||r.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let i={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},n=G(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:r,nextRun:i,evidenceHash:n,eventData:{fromSchema:Xe,toSchema:Ye,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function WJ(e){let{journal:t,state:r}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=fc(r,t.previousState),a=fc(r,t.nextState);if(!n&&!a)throw new Error(`Native change ${r.name} does not match its v2 evidence transition`);let o=V(e.paths,r.name),s=await pt(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${r.name}`);let c=t.previousRun!==null&&En(s,t.previousRun),l=En(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${r.name}`);let d=(await Zt(o,t.nextRun.trajectoryRef)).map((g,w)=>({event:g,index:w})).filter(({event:g})=>g.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!EN(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Cp(r),revision:r.revision+(r.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,h=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,m=G(JSON.stringify({operation:"supersede-v2-evidence-transition",change:r.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:p.revision}));return{nextState:p,plan:{sourceHash:await Br(Mt(e.paths,r.name)),transitionId:t.id,previousRun:v,nextRun:h,evidenceHash:m,eventData:{fromSchema:Xe,toSchema:Ye,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function zJ(e){let t,r,i,n;if(e.state.schema===Kt){if(t=kN(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==to)throw new Error("Native v1 change has a transition from another schema generation");let s=jJ(e.pendingTransition.journal);if(_I(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(_I(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Mt(e.paths,e.name);r={sourceHash:await Br(c),targetHash:G(AI(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Qi)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await WJ({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,i=l.plan}else{let l=$J(s);if(fc(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(fc(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Mt(e.paths,e.name);r={sourceHash:await Br(u),targetHash:G(AI(l)),nextJournal:l}}}else t=Cp(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await VJ({paths:e.paths,state:e.state,migrationId:e.id}));let a=SN.join(se(e.paths,e.name),lt),o=(0,xp.stringify)(RN(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Kt?Xe:Ye,sourceHash:await Br(a),targetHash:G(o),createdAt:e.now.toISOString(),nextState:t,...r?{transition:r}:{},...i?{transitionSupersede:i}:{},...n?{runRetreat:n}:{}}}async function OI(e){return $(e.paths,`migrate schema for ${e.name}`,()=>Mi(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let r=await LJ(e.paths,e.name,e.hooks);if(r?.schema===Ye)return r;let i=await Vr(e.paths,e.name);if(i.status==="current"&&i.state)return i.state;if(i.status!=="migration-required"||!i.state)throw new Error(i.message??`Native change ${e.name} cannot be migrated`);if(await $s(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=i.state;if(n.schema!==Kt&&n.schema!==Xe)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Vy(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await zJ({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??xJ()}),s=Lu(e.paths,e.name),c=F(e.paths,s);await j(c,s),await fe(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}oo();Ir();sn();au();Js();var Rn=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),UJ=512*1024,Fo=/^([a-f0-9]{64})\.json$/u,KJ=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,YJ=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Ap=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function xN(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wi(e,t){return xN(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function FI(e,t){return xN(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function hc(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ir(e,t){return e<t?-1:e>t?1:0}function XJ(e,t){let r=qe.relative(e.projectRoot,t);if(r.length===0||qe.isAbsolute(r)||r===".."||r.startsWith(`..${qe.sep}`))throw new Error("Native evidence retention finding path is outside the project");return r.split(qe.sep).join("/")}function MI(e,t){return qe.join(V(e,t),"evidence")}function _p(e,t){return XJ(e,MI(e,t))}async function Ip(e,t){let r=qe.resolve(e),i=qe.resolve(t);if(!q(r,i))throw new Error("Native evidence retention path escapes its managed change");let n=qe.relative(r,i).split(qe.sep).filter(Boolean),a=[],o=r;for(let s of["",...n]){s&&(o=qe.join(o,s));let c=await Se.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Se.realpath(o);if(a.length>0&&!q(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...hc(c)})}return a}async function Yr(e){for(let t of e){let r=await Se.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!xN(t,r)||await Se.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function LI(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:fi(e,t)}function HI(e){return e!==null&&YJ.test(e)?[e]:[]}function QJ(e,t,r,i){if(e==="snapshots")return{canonical:qs(r,t),dependencies:[]};if(e==="scopes"){let a=Ms(r);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Ch(r);if(a.change!==i||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[fi("scopes",a.scopeHash)]}}if(e==="verifications"){let a=nu(r);if(a.change!==i||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(HI));return{canonical:a,dependencies:[a.implementationScopeRef,kw(a.reportHash),...HI(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Native report evidence must be an object");let a=r;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||JJ("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=cu(r);if(a.bindings.change!==i||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=un(r);if(n.change!==i||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Ta(e){let t=await Se.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let r=e.kind==="check-receipts"?UJ:Wr;if(t.size>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let i=await Se.realpath(e.file);if(!q(e.directoryChain[0].realPath,i))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":PN.O_RDONLY|PN.O_NOFOLLOW|PN.O_NONBLOCK,a=await Se.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Se.lstat(e.file),Se.realpath(e.file)]);if(await Yr(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==i||!Wi(hc(t),o)||!Wi(hc(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let w=r+1-d,S=await a.read(u,0,Math.min(u.length,w),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,d>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,S.bytesRead)))}let[f,p,v]=await Promise.all([a.stat(),Se.lstat(e.file),Se.realpath(e.file)]);if(await Yr(e.directoryChain),!p.isFile()||p.isSymbolicLink()||v!==i||!Wi(hc(o),f)||!Wi(hc(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let h=Buffer.concat(l,d).toString("utf8"),m;try{m=JSON.parse(h)}catch(w){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:w})}let g=QJ(e.kind,e.hash,m,e.name);if(h!==JSON.stringify(g.canonical,null,2)+`
|
|
304
|
+
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:hc(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(ir)}}finally{await a.close()}}async function DI(e){try{return await Se.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function ZJ(e){let t=V(e.paths,e.name),r=t,i=MI(e.paths,e.name);await j(F(e.paths,i),i);let n;try{let s=await Ip(t,i);n=await Se.readdir(i,{withFileTypes:!0}),await Yr(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Ap){if(!n.some(f=>f.name===s))continue;let c=qe.join(i,s),l=await Ip(t,c),u=(await Se.readdir(c,{withFileTypes:!0})).sort((f,p)=>ir(f.name,p.name)),d=new Map;for(let f of u){let p=KJ.exec(f.name);if(!p)continue;let v=d.get(p[1])??[];v.push(f),d.set(p[1],v)}for(let[f,p]of[...d.entries()].sort(([v],[h])=>ir(v,h))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=p[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let h=qe.join(c,f),m=Fo.exec(f)?.[1];if(!m)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let g=LI(s,m),w=qe.join(c,v.name),S=await Ta({changeRoot:r,file:w,ref:g,kind:s,hash:m,name:e.name,directoryChain:l}),N=await DI(h),y=N?null:await Ta({changeRoot:r,file:h,ref:g,kind:s,hash:m,name:e.name,directoryChain:l});a.push({ref:g,original:h,quarantine:w,document:S,action:N?"restore-original":"finish-linked-recovery",originalDocument:y})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(ir);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:pc(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Tp(o)}`),path:_p(e.paths,e.name)}]};for(let s of a.sort((c,l)=>ir(c.ref,l.ref))){if(await Yr(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Ta({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Ta({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Wi(s.originalDocument.identity,d.identity)||!Wi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Se.rm(s.quarantine),await Yr(s.document.directoryChain);continue}if(!await DI(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Se.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Wi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Se.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Ta({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Ta({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Fo.exec(qe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!FI(s.document.identity,l.identity)||!Wi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Se.rm(s.quarantine),await Yr(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:pc(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Tp(o)}`),path:_p(e.paths,e.name)}]}}async function eG(e,t){let r=V(e,t),i=r,n=qe.join(r,"evidence");await j(F(e,n),n);let a;try{let l=await Ip(r,n);a=await Se.readdir(n,{withFileTypes:!0}),await Yr(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Ap.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(ir);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Tp(o)}`);let s=[],c=0;for(let l of Ap){if(!a.some(p=>p.name===l))continue;let u=qe.join(n,l),d=await Ip(i,u),f=(await Se.readdir(u,{withFileTypes:!0})).sort((p,v)=>ir(p.name,v.name));await Yr(d);for(let p of f){if(s.length>=Rn.maxDocuments)throw new Error(`Native evidence store exceeds ${Rn.maxDocuments} documents`);let v=Fo.exec(p.name);if(!v||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let h=LI(l,v[1]),m=qe.join(u,p.name);await j(F(e,m),m);let g=await Ta({changeRoot:i,file:m,ref:h,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=g.size,c>Rn.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Rn.maxScannedBytes} scanned bytes`);s.push(g)}await Yr(d)}return s}function BI(e,t){let r=new Set,i=[...e].sort(ir).reverse();for(;i.length>0;){let n=i.pop();if(r.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);r.add(n);for(let o of[...a.dependencies].sort(ir).reverse())r.has(o)||i.push(o)}return r}function tG(e){let t=new Map(e.map(a=>[a.ref,a])),r=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&r.set(o,(r.get(o)??0)+1);let i=[...r].filter(([,a])=>a===0).map(([a])=>a).sort(ir),n=[];for(;i.length>0;){let a=i.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=r.get(s);if(c===void 0)continue;let l=c-1;r.set(s,l),l===0&&(i.push(s),i.sort(ir))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function rG(e,t,r){let i=new Map(e.map(c=>[c.ref,c]));if(i.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!i.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=BI(t,i),a=new Set(n);for(let c of e)r-c.mtimeMs<Rn.minimumAgeMs&&a.add(c.ref);for(let c of Ap){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||ir(u.ref,d.ref)).slice(0,Rn.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=BI(a,i),s=e.filter(c=>!o.has(c.ref)&&r-c.mtimeMs>=Rn.minimumAgeMs).sort((c,l)=>ir(c.ref,l.ref));return{candidates:tG(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Tp(e){let t=e.slice(0,Rn.maxReportedRefs),r=e.length-t.length;return`${t.join(", ")}${r>0?`, ... (${r} more)`:""}`}function pc(e){let t=Rn.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let r=e;for(;r.length>0&&Buffer.byteLength(`${r}...`,"utf8")>t;)r=r.slice(0,-1);return`${r}...`}function CN(e,t,r,i){let n=t.candidates.map(a=>a.ref).sort(ir);return{severity:"info",code:r?"evidence-retention-cleaned":"evidence-retention-candidates",message:pc(`${r?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Tp(n)}`),path:i}}async function qI(e,t){try{await Se.lstat(t);return}catch(r){if(r.code!=="ENOENT")return}try{await Se.rename(e,t)}catch{}}async function iG(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Yr(e.directoryChain);let r=await Ta({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Fo.exec(qe.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),i=await Se.lstat(e.file),n=await Se.realpath(e.file);if(!i.isFile()||i.isSymbolicLink()||!Wi(e.identity,i)||!Wi(e.identity,r.identity)||!q(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=qe.join(qe.dirname(e.file),`.${qe.basename(e.file)}.${GJ()}.gc`);await Se.rename(e.file,a);try{let[o,s]=await Promise.all([Se.lstat(a),Se.realpath(a)]);if(await Yr(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!FI(e.identity,o)||!q(e.directoryChain[0].realPath,s))throw await qI(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Se.rm(a),await Yr(e.directoryChain)}catch(o){throw await qI(a,e.file),o}}async function nG(e){if((await X(e.projectRoot))?.native.pending_root_move)return!0;let r;try{r=await Se.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of r){if(!i.isDirectory()||i.isSymbolicLink())return!0;try{let n=await ur(e,i.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function aG(e,t){if(t)return[t];let r;try{r=await Se.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort(ir)}async function oG(e,t){let r=await Vr(e,t);if(r.status!=="current"||!r.state||r.state.archived)return!0;let[i,n,a]=await Promise.all([bn(e,t),Vu(e,t),Ca(e,t)]);return i!==null||n!==null||a!==null}async function sG(e){if(await oG(e.paths,e.name))return[];let t=await Vr(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let r=await ZJ({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(r.pending)return r.findings;let i=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&i.push(c);let n=await eG(e.paths,e.name),a=rG(n,i,e.nowMs);if(a.candidates.length===0)return r.findings;let o=_p(e.paths,e.name);if(!e.repair)return[...r.findings,CN(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await iG(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...r.findings,...s.length>0?[CN(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:pc(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...r.findings,CN(e.name,a,!0,o)]}async function VI(e){if(e.deferAll||await nG(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let r=async n=>{let a=[];for(let o of await aG(e.paths,e.name))try{a.push(...await sG({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:pc(`Native evidence retention refused to clean ${o}: ${s.message}`),path:_p(e.paths,o)})}return a};if(!(e.repair??!1))return r(!1);let i=await r(!1);if(i.some(n=>n.severity==="error")||!i.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return i;try{return await $(e.paths,"prune Native evidence",()=>r(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:pc(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}Qa();Q();Yt();Oe();tt();Qa();Q();Yt();oo();Lr();import{createHash as cG,randomUUID as lG}from"crypto";import{promises as ja}from"fs";import Pe from"path";var _N=64*1024*1024,uG=256*1024,GI=16*1024*1024;async function Nt(e){try{return await ja.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dG(e){let t;try{t=await ja.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t){if(!r.isDirectory()||r.isSymbolicLink())continue;let i;try{i=await ur(e,r.name)}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction ${r.name} has no journal; run doctor before moving`,{cause:n}):n}if(i.status!=="committed"&&i.status!=="rolled-back")throw new Error(`Native transaction ${i.id} is unfinished; recover it before moving`)}}async function fG(e,t){for(let r of await ja.readdir(e.locksDir,{withFileTypes:!0})){let i=Pe.join(e.locksDir,r.name);if(Pe.resolve(i)!==Pe.resolve(t)&&(r.isFile()||r.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${i}`)}}async function hG(e){let t;try{t=await ja.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name))){if(!r.isDirectory()||r.isSymbolicLink())continue;let i=await Dt(e,r.name);if(i){await uh({paths:e,name:r.name,revision:i.capturedRevision,...i.schema==="comet.native.workspace.v3"?{binding:{isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch},...i.finish?{finish:i.finish}:{}}:{}});continue}}}async function pG(e){let t;try{t=await ja.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name)))if(!(!r.isDirectory()||r.isSymbolicLink()))try{let i=await Dt(e,r.name);if(i?.schema==="comet.native.workspace.v3"){let n=await _i({paths:e,identity:i});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(i){let n=await sa({paths:e,identity:i});if(n.state!=="aligned")throw new Error(`legacy workspace ownership is ${n.state}`)}}catch(i){throw new Error(`Native workspace identity for ${r.name} must be aligned and repaired before moving the root`,{cause:i})}}async function zu(e,t){let r=[];async function i(n){let a=await lr({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=Pe.join(n,s.name);if(t.excludedFiles?.has(Pe.resolve(c))){await a.verify();continue}let l=await ja.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())r.push({ref:Pe.relative(e,c).split(Pe.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await Te({root:e,file:c,maxBytes:_N,label:`Native root file ${Pe.relative(e,c)}`});r.push({ref:Pe.relative(e,c).split(Pe.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await i(e),r.sort((n,a)=>n.ref.localeCompare(a.ref))}async function mG(e,t,r,i){await Ci({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await lr({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=Pe.join(a,l.name);if(Pe.resolve(u)===Pe.resolve(r)){await s.verify();continue}let d=await ja.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=Pe.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Ci({root:i,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Zn({sourceRoot:e,source:u,targetRoot:i,target:f,maxBytes:_N,label:`Native root move file ${Pe.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function mc(e,t,r,i){let n=await zu(e,{rejectSymlinks:!0,excludedFiles:r?new Set([Pe.resolve(r)]):void 0}),a=await zu(t,{rejectSymlinks:!0,excludedFiles:i?new Set([Pe.resolve(i)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function UI(e,t){return Pe.join(e.artifactRoot,`.comet-native-move-${t}`)}function vG(e,t){return Pe.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function gG(e){return`${e}.removing`}function WI(e,t){return Pe.join(Pe.dirname(e),`.${Pe.basename(e)}.${t}.rollback-removing`)}function KI(e,t,r){return Pe.join(Wf(e,t).directory,`root-move-cleanup-${r}.json`)}function wG(e){return JSON.stringify(e,null,2)+`
|
|
305
|
+
`}function yG(e){return cG("sha256").update(e).digest("hex")}function NG(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let r=e,i=Object.keys(r).sort(),n=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||Pe.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function bG(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let i=e;if(JSON.stringify(Object.keys(i).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||i.schema!=="comet.native.root-move-cleanup.v1"||i.transactionId!==t||i.kind!==r||!Array.isArray(i.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=i.entries.map(NG);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=Pe.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:r,entries:n}}async function kG(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=wG(t);if(Buffer.byteLength(r,"utf8")>GI)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await xe(KI(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),yG(r)}async function SG(e){let t=await Te({root:e.paths.runtimeDir,file:KI(e.paths,e.id,e.cleanup.kind),maxBytes:GI,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return bG(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function AN(e){let t=await zu(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(i=>[i.ref,i]));for(let i of t){let n=r.get(i.ref);if(!n||JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${i.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function zI(e){return e.ref.split("/").length}async function EG(e){let r=[...await AN({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>zI(a)-zI(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=Pe.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await qf({root:e.projectRoot,file:a,maxBytes:_N,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await cg({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),i+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,i)}await AN({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await cg({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function jp(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function YI(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function RG(e,t,r,i){for(let a of[e,t])try{let o=await ur(a,i);if(o.kind!=="root-move")throw new Error(`Transaction ${i} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=Pe.join(r,"runtime","transactions",i,"transaction.json");try{let a=await Te({root:r,file:n,maxBytes:uG,label:`Staged Native root-move journal ${i}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${i}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${i}`,{cause:a})}}async function JI(e){let t=jp(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Nr(e.projectRoot,t),t}async function Wu(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=jp(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await Nr(e.projectRoot,r),r}async function $p(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=r.cleanup;if(i&&i.kind!==e.kind)throw new Error(`Native root move has unfinished ${i.kind} cleanup; cannot start ${e.kind}`);let n=await Nt(e.target),a=await Nt(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!i){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await kG({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await zu(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Wu({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await SG({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await Nt(e.target),a=await Nt(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(i.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await VE({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(i.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Wu({projectRoot:e.projectRoot,config:t,id:e.id})}return await AN({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Wu({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Wu({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await EG({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Wu({projectRoot:e.projectRoot,config:t,id:e.id})}async function XI(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await Nt(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=gG(e.staging);t=await $p({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await zu(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([Pe.resolve(e.lockFile)])}),await mG(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await mc(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await JI({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await Nt(e.destinationPaths.nativeRoot)){if(await Nt(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await mc(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await Nt(e.staging))throw new Error("Native move staging tree is missing");await mc(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await ja.rename(e.staging,e.destinationPaths.nativeRoot)}t=await JI({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await Nt(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=vG(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await Nt(e.sourcePaths.nativeRoot)&&await mc(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await $p({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:i,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await hG(e.destinationPaths);let n=await ur(e.destinationPaths,e.pending.id);await ws(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await Nr(e.projectRoot,o),o}async function QI(e){let t=await X(e.projectRoot)??Ya("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let r=zn(e.toArtifactRoot);if(r===t.native.artifact_root)throw new Error(`Native artifact root is already ${r}`);let i=await pe(e.projectRoot,t.native.artifact_root),n=await pe(e.projectRoot,r);if(q(i.nativeRoot,n.nativeRoot)||q(n.nativeRoot,i.nativeRoot))throw new Error("Native source and destination roots must not overlap");if(!await Nt(i.nativeRoot))throw new Error(`Native source root does not exist: ${i.nativeRoot}`);if(await dG(i),await Nt(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await Ki(i,"root-move",`move root to ${r}`),o=lG(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:r,stage:"copying"},c=YI({id:o,paths:i,now:e.now??new Date}),l=UI(n,o);try{if(await fG(i,a.file),await pG(i),await Nt(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Nr(e.projectRoot,jp(t,s)),await mg(i,c),await e.hooks?.afterRootMoveStage?.("copying",c),await XI({projectRoot:e.projectRoot,config:jp(t,s),pending:s,sourcePaths:i,destinationPaths:n,staging:l,journal:c,lockFile:a.file,hooks:e.hooks}),{fromNativeRoot:i.nativeRoot,toNativeRoot:n.nativeRoot,transactionId:o}}finally{await Yi(a)}}async function ZI(e){let t=await X(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let i=await pe(e.projectRoot,r.fromArtifactRoot),n=await pe(e.projectRoot,r.toArtifactRoot),a=UI(n,r.id),o=await Nt(i.nativeRoot)?i:n,s=await Ki(o,"root-move",`recover root ${r.id}`);try{let c;try{c=await RG(i,n,a,r.id)}catch(v){if(r.stage!=="copying"||!await Nt(i.nativeRoot))throw v;let h=YI({id:r.id,paths:i,now:new Date});await mg(i,h),c={journal:h,paths:i}}if(e.strategy==="continue"){let v=await XI({projectRoot:e.projectRoot,config:t,pending:r,sourcePaths:i,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await Nt(i.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=WI(n.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await Nt(n.nativeRoot)&&await mc(i.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await $p({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-destination",stablePaths:i,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=WI(a,r.id);!t.native.pending_root_move?.cleanup&&await Nt(a)&&await mc(i.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await $p({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-staging",stablePaths:i,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await ur(i,r.id);await zf(i,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},p={...t,native:{...f,artifact_root:r.fromArtifactRoot}};return await Nr(e.projectRoot,p),{activeNativeRoot:i.nativeRoot,config:p}}finally{await Yi(s)}}oo();Il();Lr();var vc=4096,PG=4096,CG=1024;async function $a(e,t,r){try{let i=await lr({root:F(e,t),directory:t,label:"Native doctor directory",maxEntries:r});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function Hp(e,t){let r=new Map(e.map(i=>[bt.resolve(i.file),{...i,file:bt.resolve(i.file)}]));for(let{paths:i,file:n}of r.values()){let a;try{a=await ul(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await Gv(i,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function xG(e,t){let r=Pu(e),i;try{await j(e.projectRoot,r);let n=await Ru(e);if(!n)return[];i=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:r}]}if(i.schema!=="comet.selection.v2"||i.workflow!=="native"||typeof i.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:r}];try{return await _e(e,i.change)?[]:(await Be(e,i.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:r}]}return t?(await Op.rm(r,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${i.change}`,path:r}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${i.change}`,path:r}]}async function AG(e){let t=[];for(let r of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await j(F(e,r),r)}catch(i){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${i.message}`,path:r})}return t}async function _G(e,t){let r=[],i=[];for(let n of await $a(e,e.transactionsDir,PG)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await ur(e,n.name)}catch(o){r.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:bt.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){i.push(a),r.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await Xa([e],`doctor archive recovery ${a.id}`,async()=>await Hp([{paths:e,file:bt.join(e.locksDir,"root-move.lock")},{paths:e,file:bt.join(e.locksDir,"archive.lock")}],r)?(await Q_({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){i.push(a);continue}r.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){i.push(a),r.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else i.push(a),r.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:r,unfinished:i}}async function IG(e,t,r){let i=[];for(let n of await $a(e,e.locksDir,CG)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=bt.join(e.locksDir,n.name);try{let o=await ul(a);if(o.status==="active")i.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")i.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&r.length===0){let s=await Gv(e,a,o);s.status==="removed"?i.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&i.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else i.push({severity:r.length>0?"error":"warning",code:"lock-stale",message:r.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){i.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return i}async function TG(e,t,r=5){let i=[],n=t?await bN(e,{maxVerifyFailures:r}).then(a=>a.filter(o=>o.name===t)):await bN(e,{maxVerifyFailures:r});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){i.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:bt.join(e.changesDir,a.name,lt)});continue}let o=await Ia(e,a.name,{details:!0,maxVerifyFailures:r});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||i.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:bt.join(e.projectRoot,s.path)}:{}})}return i}async function jG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{let a=await xs(e,n);if(a.status!=="repairable")continue;if(!t.repair){r.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await YR(e,n);o&&r.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){r.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:bt.join(V(e,n),"trajectory.jsonl")})}return r}async function $G(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=await ll(e,n);if(a.status==="missing"){r.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){r.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=Ka(e,n),s=He(e,n);if(!t.repair){r.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await Xa([e],`migrate Runtime layout for ${n}`,async()=>{let c=await br({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await j(e.runtimeDir,s),await Op.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await br({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Op.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Op.rename(o,s)}),r.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){r.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return r}async function OG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{if(!await Bg(e,n))continue;if(!t.repair){r.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:_s(e,n),repair:"migrate"});continue}let a=await Be(e,n);await oP({paths:e,name:n,revision:a.revision})&&r.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:_s(e,n)})}catch(a){r.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:_s(e,n)})}return r}async function HG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=Lu(e,n);try{let o=await Vu(e,n),s=await Vr(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){r.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:bt.join(e.changesDir,n,lt)});continue}if(!t.repair){r.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:bt.join(e.changesDir,n,lt),repair:"migrate"});continue}await OI({paths:e,name:n}),r.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:bt.join(e.changesDir,n,lt)})}catch(o){if(o.code==="ENOENT")continue;r.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return r}async function DG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a;try{a=await bn(e,n)}catch(o){if(o instanceof $u)continue;r.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Mt(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Xa([e],`doctor transition recovery ${n}`,async()=>await Hp([{paths:e,file:bt.join(e.locksDir,"root-move.lock")},{paths:e,file:bt.join(e.locksDir,`transition-${n}.lock`)}],r)?(await f_(e,n),!0):!1))continue;r.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Mt(e,n)})}catch(o){r.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Mt(e,n)})}continue}r.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Mt(e,n),repair:"continue"})}}return r}async function BG(e,t){let r=[],i=t.name?[t.name]:(await $a(e,e.changesDir,vc)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=Pa(e,n),o;try{o=await Ca(e,n)}catch(s){if(s.code==="ENOENT")continue;r.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){r.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await Xa([e],`doctor checkpoint recovery ${n}`,async()=>await Hp([{paths:e,file:bt.join(e.locksDir,"root-move.lock")},{paths:e,file:bt.join(e.locksDir,`transition-${n}.lock`)}],r)?(await S_(e,n),!0):!1))continue;r.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){r.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return r}async function Ju(e){let t=e.repair??!1,r=[],i=e.paths,n;try{n=await X(i.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:i.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([pe(i.projectRoot,c.fromArtifactRoot),pe(i.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Hp([{paths:l,file:bt.join(l.locksDir,"root-move.lock")},{paths:u,file:bt.join(u.locksDir,"root-move.lock")}],r))return{healthy:!1,findings:r};let f=await ZI({projectRoot:i.projectRoot,strategy:e.recoveryStrategy});i=await pe(i.projectRoot,f.config.native.artifact_root),a=!1,r.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return r.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:r}}else r.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await AG(i);if(r.push(...o),o.length>0)return{healthy:!1,findings:r};let s=await _G(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return r.push(...s.findings),e.projectOnly||(r.push(...await $G(i,{name:e.name,repair:t})),r.push(...await HG(i,{name:e.name,repair:t})),r.push(...await OG(i,{name:e.name,repair:t})),r.push(...await jG(i,{name:e.name,repair:t})),r.push(...await DG(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),r.push(...await BG(i,{name:e.name,repair:t})),r.push(...await VI({paths:i,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),r.push(...await IG(i,t,s.unfinished)),r.push(...await xG(i,t)),e.projectOnly||r.push(...await TG(i,e.name,n?.native.max_verify_failures??5)),{healthy:r.every(c=>c.severity==="info"),findings:r}}ga();zt();ga();hn();import{promises as rT}from"node:fs";import nT from"node:path";import eT from"node:path";function tT(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Vt(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:tT(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:tT(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>eT.relative(t.projectRoot,eT.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}function aT(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function oT(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function sT(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(i=>({kind:"supervisor-child",value:FG(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:MG(i,r)}))]:[]]}function cT(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function iT(e,t){let r=ne(e.projectRoot),i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:nT.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function IN(e){let{state:t,paths:r}=e,i=Vt(t),n=e.details?sT(t,null,[]):[],a=oT(e.cursor,t.state_version,0),o=n.slice(a,a+32),s=a+o.length<n.length?aT(t.state_version,0,a+o.length):null;return{schema:"comet.native.status.v2",name:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,archived:!0,archiveRef:nT.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:cT(t),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:i.blockers,workspace:{projectRoot:r.projectRoot,isolation:t.workspace.isolation,bindingState:"aligned",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:null},localExecution:{status:"not-expected",operation:null},continuation:U(t),...e.details?{details:{stateVersion:t.state_version,items:o,nextCursor:s,nextPageArgs:s?["comet","native","status",t.name,"--details","--cursor",s,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function qG(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function Dp(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function FG(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:Dp(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function MG(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:Dp(e.summary,t)??""}}async function Xr(e){let t=await zx(e),r=Vt(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await vt({paths:e.paths,state:t.state}),a=await gn({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await ee(e.paths,e.name,{diagnostics:!0}),s=o?{...iT(e.paths,t.state),projectRoot:"."}:iT(e.paths,t.state),c=U(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?qG(e.paths,o):[],d=o?(()=>{let v=o.children.filter(({status:N})=>N==="pending"||N==="ready").length,h=o.children.filter(({status:N})=>N==="active"||N==="verified").length,m=o.children.filter(({status:N})=>N==="integrated"||N==="archived").length,g=o.children.filter(({status:N})=>N==="blocked"||N==="needs-reverify").length,w=o.children.filter(({status:N})=>N==="active"||N==="blocked"||N==="needs-reverify").slice(0,16).map(N=>({name:N.name,summary:N.summary,projectRoot:N.task?.projectRoot??N.projectRoot?"<worktree>":null,reason:Dp(N.blocker,u)})),S=o.children.flatMap(({blocker:N})=>{let y=Dp(N,u);return y?[y]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:h,integrated:m,blocked:g,active:w,agents:{working:o.children.filter(({task:N})=>N!==null).length,completed:m},risks:S,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&m===o.children.length?"parent-verification":v>0?"dispatch-ready-child":g>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let v=o?.stateVersion??0,h=sT(t.state,o,u),m=oT(e.cursor,t.state.state_version,v),g=h.slice(m,m+32),w=m+g.length<h.length?aT(t.state.state_version,v,m+g.length):null;return{items:g,nextCursor:w,supervisorStateVersion:v}})():null,p=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:cT(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((v,h)=>({...v,[h.status]:(v[h.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...p?{supervisor:p}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function lT(e){let t;try{t=await rT.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let r=[];for(let i of t)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let n=await rT.readFile(`${ye(e,i.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&r.push(i.name)}catch(n){if(n.code!=="ENOENT")throw n}return r.sort((i,n)=>i.localeCompare(n,"en"))}no();async function Gu(e,t){let r=await vt({paths:e,state:t});return U(t,r)}async function LG(e){let t;try{t=await fT.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort((r,i)=>r.localeCompare(i,"en"))}function VG(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function uT(e,t){let r;try{r=await fT.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let i=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${VG(t)}$`,"u"),n=r.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&i.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:Bp.join(e.archiveDir,n.name)}:null}function WG(e){let t=new Map;for(let r of e){let i=[r.severity,r.code,r.message,r.path??""].join("\0");t.set(i,r)}return[...t.values()]}function Uu(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function dT(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Bp.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function zG(e,t){return t.status==="repairable-legacy-overlay"?{severity:"error",code:"portable-supervisor-overlay-stale",message:t.message,path:t.file,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}:t.status==="incompatible"?{severity:"error",code:"portable-supervisor-overlay-incompatible",message:t.message,path:t.file}:null}async function JG(e,t){let r=[],i=[];for(let n of await qE(e)){let a=io(n);if(t&&a.change!==t)continue;let o=Bp.join(e.transactionsDir,n);try{let s=await yl(e,n);if(!s)continue;r.push(s),i.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){i.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:r,findings:i}}async function TN(e,t){let r=It(e,"--repair"),i=Re(e,"--strategy");if(i!==void 0&&i!=="continue"&&i!=="rollback")throw new H("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();Ce(e);let a=await lI(t),o=await JG(a,n);if(n&&o.findings.length>0){if(i)throw new H("--strategy is only available to the legacy transaction doctor");let d=await _e(a,n)?await Xr({paths:a,name:n,details:!0}):void 0;if(r&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await _u({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Gu(a,v.state)})}let p=await mi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:p.schema,stateVersion:p.state_version},state:p,continuation:await Gu(a,p)})}return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await _e(a,n)){if(i)throw new H("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([uT(a,n),my(a,n)]);if(u){let m=await Xr({paths:a,name:n,details:!0});return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:m,findings:[u],continuation:m.continuation})}if(d&&!r){let m=await Xr({paths:a,name:n,details:!0});return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:m,findings:[dT(a,n)],continuation:m.continuation})}let f=await L(a,n),p=await gn({paths:a,state:f}),v=zG(n,p);if(v&&(p.status==="incompatible"||!r)){let m=await Xr({paths:a,name:n,details:!0});return Uu({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:m,findings:[v],continuation:m.continuation})}if(r){if(d){let g=await mi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:g.schema,stateVersion:g.state_version},state:g,continuation:await Gu(a,g)})}let m=await jo({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:m,continuation:await Gu(a,m.state)})}let h=await Xr({paths:a,name:n,details:!0});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:h,continuation:h.continuation})}if(n){if(r){let u=await mi({paths:a,name:n});return W("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Gu(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await lT(a),c=o;if(s.length>0||c.findings.length>0){if(i)throw new H("--strategy is only available to the legacy transaction doctor");if(r){let y=await Ju({paths:a,repair:!0,projectOnly:!0}),E=[];for(let k of c.transactions)k.kind==="archive"?await _u({paths:a,name:k.change}):await mi({paths:a,name:k.change}),E.push({kind:k.kind,change:k.change,transactionId:k.journal.id});let P=await TN([],t),b=P.data&&typeof P.data=="object"&&!Array.isArray(P.data)?P.data:{};return{...P,data:{...b,repaired:!0,repairedPortableTransactions:E,repairFindings:y.findings}}}let u=await LG(a),d=new Set(s),f=new Set(c.transactions.filter(y=>y.kind==="migration").map(({change:y})=>y)),p=u.filter(y=>!d.has(y)),[v,h,m,g,w]=await Promise.all([Promise.all(s.map(y=>Xr({paths:a,name:y}))),Promise.all(s.map(y=>uT(a,y))),Promise.all(s.map(y=>my(a,y))),Promise.all(p.map(y=>Ju({paths:a,name:y}))),Ju({paths:a,projectOnly:!0})]),S=WG([...h.filter(y=>y!==null),...s.flatMap((y,E)=>m[E]&&!f.has(y)?[dT(a,y)]:[]),...c.findings,...p.map(y=>({severity:"error",code:"portable-migration-required",message:`Native active change ${y} requires migration to portable Runtime`,path:Bp.join(a.changesDir,y,"comet-state.yaml"),repair:"migrate"})),...g.flatMap(({findings:y})=>y),...w.findings]),N={healthy:S.every(y=>y.severity==="info"),workflow:p.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:p,findings:S};return N.healthy?W("doctor",N):Uu(N)}let l=await Ju({paths:a,...n?{name:n}:{},repair:r,...i?{recoveryStrategy:i}:{}});return l.healthy?W("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}Ig();import{promises as aU}from"fs";import _r from"path";import{readFileSync as GG}from"fs";import hT from"path";var UG=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),KG=new Set(["glob","grep","listfiles","read","readfile","search","view"]),pT=["file_path","filePath","path","target_file","targetFile"],mT=["file_paths","filePaths","paths","files","targets"],vT=["operations","edits"],YG=["patch","diff","patchText","patch_text","changes"];function ON(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function jN(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function XG(e){for(let t of["tool_name","toolName","tool","name"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}return null}function QG(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!hT.isAbsolute(r.trim())))return hT.resolve(r.trim())}}function ZG(e){for(let t of["session_id","sessionId","conversation_id","conversationId"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim().slice(0,256)}}function eU(e){for(let t of["hook_event_name","hookEventName","event_name","eventName"]){let r=e[t];if(typeof r=="string"&&r.trim())return jN(r)}}function tU(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function rU(e){if(typeof e!="string")return e;let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return e;try{return JSON.parse(t)}catch{return e}}function iU(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return rU(e[t]);return e}function $N(e){let t=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let i of r)for(let n of e.matchAll(i)){let a=n[1]?.trim();a&&a!=="/dev/null"&&t.push(a)}return t}function Mo(e,t){if(typeof t=="string"){let r=t.trim();r&&e.push(r);return}if(Array.isArray(t)){for(let r of t)Mo(e,r);return}if(ON(t)){for(let r of pT)Mo(e,t[r]);for(let r of mT)Mo(e,t[r]);for(let r of vT)Mo(e,t[r])}}function nU(e,t){let r=[],i=[t,e].filter(ON);for(let n of i){for(let a of pT)Mo(r,n[a]);for(let a of mT)Mo(r,n[a]);for(let a of vT)Mo(r,n[a]);for(let a of YG){let o=n[a];typeof o=="string"&&r.push(...$N(o))}}return typeof t=="string"&&r.push(...$N(t)),[...new Set(r)]}function Ku(e,t){if(t?.trim())return{intent:"write",targets:[t.trim()],toolName:null};if(!e.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(Sy(e))}catch{let s=$N(e);return s.length>0?{intent:"write",targets:[...new Set(s)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!ON(r))return{intent:"unknown",targets:[],toolName:null};let i=XG(r),n=nU(r,iU(r)),a=QG(r),o=ZG(r);if(eU(r)==="beforeagentstart"){let s=tU(r);return{intent:"context",targets:[],toolName:null,...s?{task:s}:{},...a?{cwd:a}:{},...o?{sessionId:o}:{}}}return i&&UG.has(jN(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i&&KG.has(jN(i))?{intent:"non-write",targets:[],toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i?{intent:"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{},...o?{sessionId:o}:{}}}function gT(){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return Ku("",e);try{return Ku(GG(0,"utf8"),e)}catch{return Ku("",e)}}Ee();tt();Q();Tg();function wT(e){let t=`Native change ${e.name} is in ${e.phase}; implementation writes are only allowed in Build.`;return e.phase==="shape"?`${t} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:e.phase==="verify"?`${t} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:e.phase==="archive"?`${t} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${t} Create or select a separate Native change if this write belongs to different work.`}async function oU(e){let{projectRoot:t,paths:r,state:i,request:n}=e,a=ye(r,i.name),o=[],s=[],c=!1,l=!1,u=!1;for(let d of n.targets){let f=_r.resolve(t,d);if(!Oa(t,f)){u=!0;continue}let p=_r.relative(t,f).replaceAll("\\","/");if(p===".comet/config.yaml"){l=!0;continue}if(!Oa(r.nativeRoot,f)){if(await rh(t,f,[_r.join(t,".comet"),r.nativeRoot])){c=!0;continue}s.push(p);continue}if(!Oa(a,f))return{allowed:!1,reason:Oa(r.specsDir,f)?`Published Native specs are updated through Archive. Stage the complete target spec in ${_r.join(a,"specs",_r.relative(r.specsDir,f))}; use comet native spec sync for reference-only corrections, or revise-requirements for requirement changes.`:"Portable Native control state is Runtime-owned",workflow:"native",phase:i.phase,change:i.name};let v=_r.relative(a,f).replaceAll("\\","/");if(v==="brief.md"||v==="children.yaml"||v.startsWith("specs/")){o.push(v);continue}return{allowed:!1,reason:`${v||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:i.phase,change:i.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:i.phase,change:i.name}:o.length>0?i.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await rc({paths:r,name:i.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:i.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:i.phase,change:i.name}:s.length>0?i.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:i.phase,change:i.name}:i.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:i.phase,change:i.name}:i.phase==="verify"||i.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await tc({paths:r,name:i.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:wT(i),workflow:"native",phase:i.phase,change:i.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function Oa(e,t){let r=_r.relative(e,t);return r===""||!r.startsWith("..")&&!_r.isAbsolute(r)}function sU(e,t,r){return r.targets.length>0&&r.targets.every(i=>{let n=_r.resolve(e,i);return Oa(e,n)?_r.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||Oa(t,n):!0})}async function cU(e){let t=await X(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let r=await pe(e,t.native.artifact_root),i;try{i=await aU.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let n=[];for(let a of i.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await _e(r,a.name)){let o=await L(r,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await Be(r,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:r,changes:n}}var lU=th("nativeActiveContext",e=>cU(e));async function yT(){let{intent:e,targets:t}=await gT();return{intent:e,targets:t}}async function NT(e,t,r){let i=await lU(e);if(!i)return{allowed:!0,reason:"Native workflow is not enabled"};if(t.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.changes.length===0)return{allowed:!0,reason:sU(e,i.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"};let n;if(r){if(n=i.changes.find(l=>l.state.name===r),!n)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(i.changes.length===1)n=i.changes[0];else{let l=await Qx(i.paths);if(n=i.changes.find(u=>u.state.name===l),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(t.intent==="unknown"||t.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return oU({projectRoot:e,paths:i.paths,state:n.state,request:t});let o=!1,s=!1,c=!1;for(let l of t.targets){let u=_r.resolve(e,l);if(!Oa(e,u)){s=!0;continue}if(_r.relative(e,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(Oa(i.paths.nativeRoot,u)){o=!0;continue}if(await rh(e,u,[_r.join(e,".comet"),i.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:wT(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function bT(e,t){let r=Re(e,"--hook-output");if(r!==void 0&&r!=="copilot")throw new H("--hook-output must be copilot");Ce(e);let i=await NT(t,await yT());return r==="copilot"?{command:"hook-guard",exitCode:0,data:i,text:i.allowed?`{}
|
|
306
306
|
`:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:i.reason})}
|
|
307
307
|
`}:i.allowed?{command:"hook-guard",exitCode:0,data:i}:{command:"hook-guard",exitCode:2,data:i,error:{code:"blocked",message:i.reason}}}tt();_g();Q();async function kT(e,t){let r=Re(e,"--root"),i=await X(t),n=bp(e,i?.native.language??"en");if(Ce(e),i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let a=zn(r??i?.native.artifact_root??"docs");if(i&&r&&i.native.artifact_root!==a)throw new Error(`Configured Native artifact root is ${i.native.artifact_root}; refusing conflicting root ${a}`);let o=i?{...i,native:{...i.native,language:n,snapshot:{...i.native.snapshot,exclude:cE(i.native.snapshot.exclude)}}}:Ya(a,n),s=await pe(t,o.native.artifact_root);return await yf(s),await Ag(t),await Nr(t,o),W("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:n},`Initialized Comet Native at ${s.nativeRoot}
|
|
308
|
-
`)}tt();Q();Eh();ho();async function ST(e,t){let r=Qe(e,"change name"),i=await X(t),n=bp(e,i?.native.language??"en"),a=Re(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new
|
|
309
|
-
`)}ga();ho();tn();zt();jw();Kl();import{randomUUID as AT}from"node:crypto";import{promises as ET}from"node:fs";import Xu from"node:path";fn();it();vo();function gc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tt(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ve(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function BN(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>ve(r,`${t}[${i}]`))}function uU(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=gc(t,`Native Builder check ${r}`);if(Tt(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:ve(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function HN(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=gc(t,`Native Runtime check ${r}`);if(Tt(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:ve(i.id,`Native Runtime check ${r} id`),name:ve(i.name,`Native Runtime check ${r} name`),executable:ve(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:ve(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function RT(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:ve(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function dU(e){let t=gc(e,"Native Supervisor evidence");return Tt(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence"),{summary:ve(t.summary,"Native Supervisor evidence summary"),checks:BN(t.checks,"Native Supervisor evidence checks"),acceptance:Nh(t.acceptance),...t.receiptRef===null?{}:{receiptRef:ve(t.receiptRef,"Native Supervisor receipt ref")}}}function fU(e){let t=gc(e,"Native Runner input");if(t.kind==="builder-handoff"){Tt(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=gc(t.review,"Native Builder review");if(Tt(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:ve(t.summary,"Native Builder summary"),addressed_acceptance_ids:BN(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:uU(t.checks),known_limits:BN(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:ve(r.summary,"Native Builder review summary"),reviewer_execution_ref:ve(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return Tt(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:HN(t.checks)};if(t.kind==="verifier-response")return Tt(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return Tt(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:ve(t.summary,"Native Verifier execution error summary"),...RT(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return Tt(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:ve(t.summary,"Native unavailable Verifier summary"),...RT(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return Tt(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),candidateCommit:ve(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return Tt(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),reason:ve(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return Tt(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return Tt(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),reason:ve(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(Tt(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:dU(t.evidence)}}if(t.kind==="supervisor-checks"){if(Tt(t,["kind","child","runId","checks","materials"],"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),checks:HN(t.checks),materials:t.materials.map(r=>{let i=gc(r,"Native Supervisor material");return Tt(i,["name","content"],"Native Supervisor material"),{name:ve(i.name,"Native Supervisor material name"),content:ve(i.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate")return Tt(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:ve(t.child,"Native Supervisor child"),checks:HN(t.checks)};throw new Error("Native Runner input kind is invalid")}async function _T(e,t){let r=Xu.resolve(t,e),i=await ET.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await ET.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return fU(n)}function PT(e){return`${ut}:${e}:${AT()}`}function CT(e,t,r,i){if(Xu.resolve(A(e.projectRoot,["rev-parse","--show-toplevel"]))!==Xu.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(A(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!Er(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(A(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function hU(e,t){let r=ne(e.projectRoot),i=Xu.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Xu.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=A(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!Er(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Yu(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==ut)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function pU(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function xT(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Yu(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=pU(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:ut,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ye(t,r.name),supervisorStateRef:a?Ys(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:u,source:d})=>({capability:l,operation:u,ref:d})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function DN(e){Yu(e.state);let t=await hi(ue(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function IT(e){let t=e.input,r=await L(e.paths,e.name),i=await gn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await ee(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-checks"){let v=await Tw({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials});return{state:r,supervisorState:await ee(e.paths,e.name),supervisorTask:null,checks:[],checkExecution:v,requestChecks:null,verifierDispatch:null,continuation:K(r)}}if(n&&t.kind==="supervisor-builder-result")return $(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:N})=>N===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{CT(h.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(N){throw await ge(e.paths,Dh(v,{child:t.child,runId:t.runId,reason:N.message})),N}let m=h.task.projectRoot,g=KC(v,t),w=Dw(g,{role:"verifier",child:t.child,projectRoot:m,runId:AT()});await ge(e.paths,w.state);let S=await L(e.paths,e.name);return{state:S,supervisorTask:w.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(S)}});if(n&&t.kind==="supervisor-builder-failure")return $(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:w})=>w===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let m=Bw(v,{child:t.child,runId:t.runId,reason:t.reason});await ge(e.paths,m);let g=await L(e.paths,e.name);return{state:g,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-reconnect")return $(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:w})=>w===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{hU(h,`comet/supervisor/${v.parent}/${t.child}`)}catch(w){throw await ge(e.paths,Dh(v,{child:t.child,runId:t.runId,reason:w.message})),w}let m=GC(v,{child:t.child,runId:t.runId});await ge(e.paths,m.state);let g=await L(e.paths,e.name);return{state:g,supervisorState:m.state,supervisorTask:m.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-cancel")return $(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=Bw(v,{child:t.child,runId:t.runId,reason:t.reason});await ge(e.paths,h);let m=await L(e.paths,e.name);return{state:m,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(n&&t.kind==="supervisor-verifier-result")return $(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:S})=>S===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{CT(h.task,h.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(S){throw await ge(e.paths,Dh(v,{child:t.child,runId:t.runId,reason:S.message})),S}let m=t.evidence.receiptRef||t.verdict==="pass"?await jh({paths:e.paths,parent:e.name,task:h.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!m||m.checks.some(({status:S,exitCode:N})=>S!=="passed"||N!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=YC(v,{...t,evidence:{...t.evidence,checks:m?.checks.map(({name:S,status:N})=>`${S}: ${N}`)??[],execution:structuredClone(h.task)}});await ge(e.paths,g);let w=await L(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await XC({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks}),h=await Nu({paths:e.paths,name:e.name,trigger:"v2-integrate"}),m=h.state;return{state:m,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:K(m)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=nw().captureExecutionIdentity({identityProvider:ut,executionRef:PT("builder")}),m=await Cx({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await L(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==ut){let S=await tc({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:S,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(S)}}Yu(v);let m=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:S})=>S==="passed")?v.verification.checks:null)??(await Tx({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,g=PT("verifier"),w=await jx({paths:e.paths,name:e.name,checks:m,verifierExecutionId:g,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:w,checks:m,requestChecks:null,verifierDispatch:xT({paths:e.paths,state:w,checks:m,verifierExecutionRef:g,supervisor:a?n:null}),continuation:K(w)}}if(t.kind==="verifier-execution-error"){let v=await L(e.paths,e.name);Yu(v),await DN({paths:e.paths,state:v});let h=await Ox({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(h)}}if(t.kind==="verifier-unavailable"){let v=await Hx({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await L(e.paths,e.name),c=Yu(s),l=await DN({paths:e.paths,state:s}),u=nw(),d=u.captureExecutionIdentity({identityProvider:ut,executionRef:l}),f=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await ee(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");f=fu(v)}let p=await $x({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:d,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&p.response.kind==="final-result"){if(p.state.verification_result==="pass"&&(p.checks.length===0||p.checks.some(({status:m})=>m!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=f??await ee(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let h=hu(v,p.state);return await ge(e.paths,h),{...p,supervisorState:h,verifierDispatch:null,continuation:K(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:xT({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await DN({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:K(p.state)}}vo();fn();us();var mU=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function vU(e){let t=Re(e,"--expected-state-version"),r=Re(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new B("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new B("--expected-state-version must be a positive integer");if(!mU.has(r))throw new B("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Pn(e,t){let r=await vt({paths:e,state:t}),n=(r?.confirmed?await ee(e,t.name,{diagnostics:!0}):null)?.children.flatMap(({task:a})=>a?[a.child]:[])??[];return{...r?{childSummary:r.children.reduce((a,o)=>({...a,[o.status]:(a[o.status]??0)+1}),{total:r.children.length}),readyChildren:n.length>0?n:r.readyChildren}:{},continuation:K(t,r)}}function gU(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function TT(e){return{action:e.action,reason:e.reason,message:e.message}}async function jT(e,t){let r=Qe(e,"change name"),i=Re(e,"--summary"),n=Re(e,"--runner-input"),a=It(e,"--confirmed"),o=It(e,"--accept-result"),s=It(e,"--revise-implementation"),c=It(e,"--revise-requirements"),l=It(e,"--retry-verifier"),u=It(e,"--resolve-verifier-blocker"),d=Re(e,"--coordination-mode"),f=d;if(d!==void 0&&!_f.includes(d))throw new B("--coordination-mode must be multi-session or single-session");let p=Re(e,"--max-parallel"),v=p===void 0?2:Number(p);if(!Number.isSafeInteger(v)||v<1)throw new B("--max-parallel must be a positive integer");let h=vU(e);if([a,o,s,c,l,u].filter(Boolean).length>1)throw new B("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(f!==void 0&&(a||o||s||c||l||u||n!==void 0))throw new B("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");Ce(e);let m=await xr(t);if(!await Be(m.paths,r)){if(n)throw new B("--runner-input is only valid for portable Native changes");if(!i)throw new B("--summary is required");let b=await pi({paths:m.paths,name:r});return W("next",{state:Vt(b,m.paths),migration:{completed:!0,summary:i},continuation:K(b)})}let g=await L(m.paths,r),w=gy(m.paths,g);if(w)return W("next",{state:Vt(g,m.paths),recovery:{action:"await-user",reason:"workspace-mismatch",message:w},...await Pn(m.paths,g)});if(n){if(i||a||o||s||c||l||u||f!==void 0||h)throw new B("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let b=await ny({paths:m.paths,name:r});if(b.action==="rerun-final-verification")return W("next",{state:Vt(b.state,m.paths),...await Pn(m.paths,b.state)});let k=await jo({paths:m.paths,name:r,preserveRunningExecution:!0}),R=k.state;if(k.action==="await-user"||k.action==="done"||k.reason!=="available")return W("next",{state:Vt(R,m.paths),recovery:TT(k),...await Pn(m.paths,R)});if(R.phase==="build"){let Ne=await Ao({paths:m.paths,state:R});if(Ne.drifted){let Ue=await rc({paths:m.paths,name:r,reason:Ne.reason??"Native confirmed requirements changed"});return W("next",{state:Vt(Ue,m.paths),...await Pn(m.paths,Ue)})}let oe=await ee(m.paths,r),ce=await vt({paths:m.paths,state:R});if(ce&&!ce.allDone&&!oe)throw new B("Native parent Build advances child changes and does not accept a Builder handoff")}let I=await _T(n,t),C=await IT({paths:m.paths,name:r,input:I,maxVerifyFailures:m.config.native.max_verify_failures});return W("next",{...gU(C),state:Vt(C.state,m.paths),...await Pn(m.paths,C.state),coordination:ut})}let S=await ny({paths:m.paths,name:r});if(S.action==="rerun-final-verification")return W("next",{state:Vt(S.state,m.paths),...await Pn(m.paths,S.state)});let N=await jo({paths:m.paths,name:r}),y=N.state;if(f!==void 0&&y.phase!=="shape")throw new B("--coordination-mode is only valid when confirming Shape");if(!i)throw new B("--summary is required");let E,P=null;if(a)if(y.phase==="shape"&&y.status==="await-user"&&y.loop.next_action==="confirm-shape"){if(!h)throw new B("--expected-state-version and --expected-action are required for Shape confirmation");E=await Px({paths:m.paths,name:r,expectedContinuation:h})}else{if(y.phase==="shape")throw new B("--confirmed is only valid from the persisted Shape user confirmation boundary");if(y.phase==="verify"&&y.status==="await-user"&&y.loop.next_action==="confirm-verifier-unavailable")E=await Bx({paths:m.paths,name:r,summary:i,expectedContinuation:h});else throw new B("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!h&&(y.phase!=="verify"||y.status!=="await-user"||y.loop.next_action!=="confirm-skill-coordinated-pass"))throw new B("--accept-result is only valid for a pending Verify pass decision");E=await Dx({paths:m.paths,name:r,expectedContinuation:h})}else if(s){if(y.phase!=="verify")throw new B("--revise-implementation is only valid from Verify");E=await tc({paths:m.paths,name:r,reason:i,expectedContinuation:h})}else if(c){if(!h&&y.phase!=="verify"&&y.phase!=="archive")throw new B("--revise-requirements is only valid from Verify or Archive");E=await rc({paths:m.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:h})}else if(l)E=await Fx({paths:m.paths,name:r,expectedContinuation:h});else if(u)E=await qx({paths:m.paths,name:r,reason:i,expectedContinuation:h});else{if(N.reason!=="available")return W("next",{state:Vt(y,m.paths),recovery:TT(N),...await Pn(m.paths,y)});if(y.phase==="build"){let k=await Ao({paths:m.paths,state:y});if(k.drifted)E=await rc({paths:m.paths,name:r,reason:k.reason??"Native confirmed requirements changed"});else{let R=await vt({paths:m.paths,state:y});if(R){let I=R,C=[],Ne=[],oe=null,ce=await ee(m.paths,r);if(ce&&!R.allDone){let Ue=await UC({paths:m.paths,parent:r,maxParallel:y.coordination_mode==="single-session"?1:v});C=Ue.state.children.flatMap(({task:Ke})=>Ke?[Ke]:[]),oe=Ue.tasks.map(({child:Ke})=>Ke),Ne=Ue.state.children.flatMap(({name:Ke,blocker:jt})=>jt?[{child:Ke,message:jt}]:[]),(C.length>0||Ue.state.stateVersion!==ce.stateVersion)&&(I=await vt({paths:m.paths,state:y})??I)}if(I.allDone&&!(y.loop.stage==="repairing"&&y.verification_result==="fail"))P=await Nu({paths:m.paths,name:r,trigger:"recovery"}),E=P.state;else return W("next",{state:Vt(y,m.paths),childSummary:I.children.reduce((Ue,Ke)=>({...Ue,[Ke.status]:(Ue[Ke.status]??0)+1}),{total:I.children.length}),readyChildren:oe??I.readyChildren,...C.length>0?{supervisorTasks:C}:{},...Ne.length>0?{supervisorBlockers:Ne}:{},continuation:K(y,I)})}}}if(y.phase==="shape"&&(E=await Rx({paths:m.paths,name:r,...f===void 0?{}:{coordinationMode:f},expectedContinuation:h})),E)return W("next",{state:Vt(E,m.paths),...P?{parentAdvance:P.parentAdvance}:{},...await Pn(m.paths,E)});let b=y.phase==="shape"?await vt({paths:m.paths,state:y}):null;return{command:"next",exitCode:65,data:{state:Vt(y,m.paths),continuation:K(y,b)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return W("next",{state:Vt(E,m.paths),...f===void 0?{}:{coordinationMode:f},...await Pn(m.paths,E)})}tt();Q();async function $T(e,t){let r=Qe(e,"root subcommand");if(r==="show"){Ce(e);let i=await X(t);if(!i)throw new Error(".comet/config.yaml was not found");let n=await pe(t,i.native.artifact_root);return W("root show",{projectRoot:t,artifactRoot:i.native.artifact_root,language:i.native.language,nativeRoot:n.nativeRoot,pendingRootMove:i.native.pending_root_move??null})}if(r==="move"){let i=Qe(e,"artifact root");Ce(e);let n=await QI({projectRoot:t,toArtifactRoot:i});return W("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
310
|
-
`)}throw new
|
|
311
|
-
`)}Ee();Jt();ga();import{promises as HT}from"fs";import DT from"path";Jt();
|
|
312
|
-
`)}if(r!=="remove")throw new
|
|
313
|
-
`)}zt();ct();Ee();tt();import Cn from"node:path";import{realpathSync as bU}from"node:fs";Q();var FN=Ha(Mn(),1);tn();ct();Jt();ai();import{promises as NU}from"node:fs";import qN from"node:path";var qp=class extends Error{};async function MN(e,t){let r=await re({root:e.nativeRoot,ref:qN.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:4194304,includeHash:!1}),i=(0,FN.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new qp("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:z(i)}}async function WT(e,t){let r;try{r=await NU.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}if(r.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=qN.join(e.archiveDir,n.name,"comet-state.yaml");try{let o=await MN(e,a);o.state.archived&&o.state.status==="done"&&i.push(o)}catch(o){if(o.code==="ENOENT"||o instanceof qp)continue;let s=n.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(s,`Native archive ${n.name} is unreadable: ${o.message}`)}}return i}function Fp(e){return D("comet.native.status-record.v1",e)}function VT(e){let t=qN.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=A(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=z((0,FN.parse)(A(e.projectRoot,["show",`${r}:${t}`])));return Fp(i)===Fp(e.state)?r:null}catch{return null}}function zT(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=VT(e),i=VT(t);if(!r||!i)return!1;try{return A(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function JT(e,t){return e.state.archived&&t.state.archived&&Fp(e.state)===Fp(t.state)}Lr();var kU=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Mp(e,t){let r=Cn.normalize(LN(e)),i=Cn.normalize(LN(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function LN(e){let t=Cn.resolve(e);try{return bU.native(t)}catch{return t}}function SU(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function GT(e){let t=[];for(let r of await NN(e))t.push({name:r,kind:await Be(e,r)?"portable":"legacy"});return t}async function XT(e){let t=Cn.resolve(e),r=kt(e),i=r.length>0?r:[t];i.some(o=>Mp(o,t))||i.push(t);let n=[],a=new Set;for(let o of i.map(s=>Cn.resolve(s)).sort()){let s=Mp(o,t)?t:o,c=LN(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await X(s);if(!u)continue;let d=await pe(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await GT(d)})}if(n.length===0){let o=await X(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await pe(e,o.native.artifact_root);n.push({projectRoot:Cn.resolve(e),config:o,paths:s,changes:await GT(s)})}for(let o of n)o.archiveErrors=[],o.archives=await WT(o.paths,(s,c)=>o.archiveErrors.push({name:s,message:c}));return n}function UT(e,t){return e.workspace.bindingState==="aligned"?0:Mp(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function QT(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:u,kind:d})=>{if(d==="portable")try{let f=await Yr({paths:u.paths,name:n});return{source:u,name:n,kind:d,workspace:f.workspace,portableStatus:f,inspectionError:null}}catch(f){return{source:u,name:n,kind:d,workspace:await $l(u.paths,n),portableStatus:null,inspectionError:f instanceof Error?f.message:String(f)}}return{source:u,name:n,kind:d,workspace:await $l(u.paths,n),portableStatus:null,inspectionError:null}})),s=t.flatMap(u=>(u.archives??[]).filter(({state:d})=>d.name===n).map(d=>{let f=IN({paths:u.paths,...d});return{source:u,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:null,record:d}})),c=t.flatMap(u=>(u.archiveErrors??[]).filter(d=>d.name===n).map(d=>({source:u,error:d})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}if(s.length>0){for(let d of o)if(d.kind==="portable")try{d.record=await MN(d.source.paths,Cn.join(d.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let u=s.find(d=>[...o,...s.filter(f=>!JT(d.record,f.record))].every(f=>f.record&&zT(d.record,f.record)));if(u){i.push(u);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((u,d)=>UT(u,e)-UT(d,e)||u.source.projectRoot.localeCompare(d.source.projectRoot));let l=o.filter(u=>u.workspace.bindingState==="aligned");l.length>1?i.push(...l):l.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(l[0]??o[0])}if(i.length>Ar.maxChanges)throw new Error(`Native status discovery exceeds ${Ar.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function KT(e,t){let r=t.toString(36),i=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function EU(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=kU.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let i=D("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function YT(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?SU(r):null,nextPageArgs:r}}async function RU(e,t,r){let i=null;try{i=await fo(e.source.paths,e.name)}catch{}return i?.state?{schema:"comet.native.status.v2",name:e.name,phase:i.state.phase,status:"blocked",migrationRequired:!0,legacySchema:i.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:i.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:Ia(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function ZT(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:e.record?.state.archived?IN({paths:e.source.paths,...e.record,details:t,cursor:i}):Yr({paths:e.source.paths,name:e.name,details:t,...i?{cursor:i}:{}})}return RU(e,t,r)}async function ej(e){let t=await XT(e.projectRoot),r=(await QT(e.projectRoot,t)).filter(i=>i.name===e.name);if(r.length===0){let i=t.find(n=>Mp(n.projectRoot,e.projectRoot))??t[0];return Ia(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}if(r.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${r.map(i=>i.source.projectRoot).join(", ")}`);return ZT(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function tj(e){let t=await XT(e.projectRoot),r=await QT(e.projectRoot,t),i=D("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=EU({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+Ar.maxItems).map(u=>ZT(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<r.length?KT(i,f):null,v={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...YT(Cn.resolve(e.projectRoot),p),limits:{...Ar}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Ar.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?KT(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...YT(Cn.resolve(e.projectRoot),l),limits:{...Ar}}}async function rj(e,t){let r=It(e,"--details"),i=Re(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new B("status --details requires a change name");if(i&&n&&!r)throw new B("--cursor for a named status requires --details");Ce(e);let a=n?await ej({projectRoot:t,name:n,details:r,...i?{detailsCursor:i}:{}}):await tj({projectRoot:t,...i?{cursor:i}:{}});return W("status",a)}var PU={"hook-guard":bT,init:kT,root:$T,new:ST,spec:LT,show:FT,status:rj,select:OT,next:jT,archive:hI,check:NI,doctor:TN};async function CU(e,t){let r=e.indexOf("--help");if(e.length===0||r>=0||e[0]==="help"){let o=e[0]==="help"?e.slice(1):r>=0?e.slice(0,r):[],s;try{s=hN(o)}catch(c){throw new B(c.message)}return{command:s.topic?`${s.topic} --help`:"help",exitCode:0,data:s,text:s.usage}}let i=e.shift(),n=await cI(t),a=PU[i];if(!a)throw new B(`Unknown Native command: ${i}`);return a(e,n)}async function ij(e){let t=[...e],r=t.indexOf("--"),i=r<0?t:t.slice(0,r),n=r<0?[]:t.slice(r),a=i.includes("--json"),o=i.includes("--verbose"),s,c=i[0]??null;try{It(i,"--json"),It(i,"--verbose"),s=Re(i,"--project-root");let l=[...i,...n];return c=l[0]??null,mN(await CU(l,s),a,o)}catch(l){return mN(dI(c,l),a,o)}}async function AU(e=process.argv.slice(2)){let t=await ij(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
|
|
308
|
+
`)}tt();Q();Eh();ho();async function ST(e,t){let r=Qe(e,"change name"),i=await X(t),n=bp(e,i?.native.language??"en"),a=Re(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new H("--isolation must be current, branch, or worktree");let o=Re(e,"--change-branch"),s=Re(e,"--target-branch"),c=Re(e,"--worktree-path");Ce(e);let l=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let u=await Xl({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:l});t=u.projectRoot,i=await X(t);let d=i===null?Ya("docs",n):void 0;if(i||(i=d),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let f=await pe(t,i.native.artifact_root);await yf(f);let p=await Ex({paths:f,name:r,language:n,workspaceBinding:u.binding,...d?{initialProjectConfig:d}:{}});return await Yh(f,p.name),d&&await ph(t),W("new",{...p,preparation:u.preparation,continuation:U(p)},`Created Native change ${p.name}
|
|
309
|
+
`)}ga();ho();rn();zt();jw();Kl();import{randomUUID as AT}from"node:crypto";import{promises as ET}from"node:fs";import Xu from"node:path";hn();it();vo();function gc(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Tt(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ve(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function BN(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>ve(r,`${t}[${i}]`))}function uU(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=gc(t,`Native Builder check ${r}`);if(Tt(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:ve(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function HN(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=gc(t,`Native Runtime check ${r}`);if(Tt(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:ve(i.id,`Native Runtime check ${r} id`),name:ve(i.name,`Native Runtime check ${r} name`),executable:ve(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:ve(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function RT(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:ve(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function dU(e){let t=gc(e,"Native Supervisor evidence");return Tt(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence"),{summary:ve(t.summary,"Native Supervisor evidence summary"),checks:BN(t.checks,"Native Supervisor evidence checks"),acceptance:Nh(t.acceptance),...t.receiptRef===null?{}:{receiptRef:ve(t.receiptRef,"Native Supervisor receipt ref")}}}function fU(e){let t=gc(e,"Native Runner input");if(t.kind==="builder-handoff"){Tt(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=gc(t.review,"Native Builder review");if(Tt(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:ve(t.summary,"Native Builder summary"),addressed_acceptance_ids:BN(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:uU(t.checks),known_limits:BN(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:ve(r.summary,"Native Builder review summary"),reviewer_execution_ref:ve(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return Tt(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:HN(t.checks)};if(t.kind==="verifier-response")return Tt(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return Tt(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:ve(t.summary,"Native Verifier execution error summary"),...RT(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return Tt(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:ve(t.summary,"Native unavailable Verifier summary"),...RT(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return Tt(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),candidateCommit:ve(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return Tt(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),reason:ve(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return Tt(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return Tt(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),reason:ve(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(Tt(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:dU(t.evidence)}}if(t.kind==="supervisor-checks"){if(Tt(t,["kind","child","runId","checks","materials"],"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:ve(t.child,"Native Supervisor child"),runId:ve(t.runId,"Native Supervisor runId"),checks:HN(t.checks),materials:t.materials.map(r=>{let i=gc(r,"Native Supervisor material");return Tt(i,["name","content"],"Native Supervisor material"),{name:ve(i.name,"Native Supervisor material name"),content:ve(i.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate")return Tt(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:ve(t.child,"Native Supervisor child"),checks:HN(t.checks)};throw new Error("Native Runner input kind is invalid")}async function _T(e,t){let r=Xu.resolve(t,e),i=await ET.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await ET.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return fU(n)}function PT(e){return`${ut}:${e}:${AT()}`}function CT(e,t,r,i){if(Xu.resolve(A(e.projectRoot,["rev-parse","--show-toplevel"]))!==Xu.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(A(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!Er(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(A(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function hU(e,t){let r=ne(e.projectRoot),i=Xu.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Xu.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=A(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!Er(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{A(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Yu(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==ut)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function pU(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function xT(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Yu(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=pU(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:ut,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ye(t,r.name),supervisorStateRef:a?Ys(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:u,source:d})=>({capability:l,operation:u,ref:d})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function DN(e){Yu(e.state);let t=await pi(ue(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function IT(e){let t=e.input,r=await L(e.paths,e.name),i=await gn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await ee(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-checks"){let v=await Tw({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials});return{state:r,supervisorState:await ee(e.paths,e.name),supervisorTask:null,checks:[],checkExecution:v,requestChecks:null,verifierDispatch:null,continuation:U(r)}}if(n&&t.kind==="supervisor-builder-result")return $(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:N})=>N===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{CT(h.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(N){throw await ge(e.paths,Dh(v,{child:t.child,runId:t.runId,reason:N.message})),N}let m=h.task.projectRoot,g=KC(v,t),w=Dw(g,{role:"verifier",child:t.child,projectRoot:m,runId:AT()});await ge(e.paths,w.state);let S=await L(e.paths,e.name);return{state:S,supervisorTask:w.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(S)}});if(n&&t.kind==="supervisor-builder-failure")return $(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:w})=>w===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let m=Bw(v,{child:t.child,runId:t.runId,reason:t.reason});await ge(e.paths,m);let g=await L(e.paths,e.name);return{state:g,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(g)}});if(n&&t.kind==="supervisor-reconnect")return $(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:w})=>w===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{hU(h,`comet/supervisor/${v.parent}/${t.child}`)}catch(w){throw await ge(e.paths,Dh(v,{child:t.child,runId:t.runId,reason:w.message})),w}let m=GC(v,{child:t.child,runId:t.runId});await ge(e.paths,m.state);let g=await L(e.paths,e.name);return{state:g,supervisorState:m.state,supervisorTask:m.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(g)}});if(n&&t.kind==="supervisor-cancel")return $(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=Bw(v,{child:t.child,runId:t.runId,reason:t.reason});await ge(e.paths,h);let m=await L(e.paths,e.name);return{state:m,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}});if(n&&t.kind==="supervisor-verifier-result")return $(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await ee(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:S})=>S===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{CT(h.task,h.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(S){throw await ge(e.paths,Dh(v,{child:t.child,runId:t.runId,reason:S.message})),S}let m=t.evidence.receiptRef||t.verdict==="pass"?await jh({paths:e.paths,parent:e.name,task:h.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!m||m.checks.some(({status:S,exitCode:N})=>S!=="passed"||N!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=YC(v,{...t,evidence:{...t.evidence,checks:m?.checks.map(({name:S,status:N})=>`${S}: ${N}`)??[],execution:structuredClone(h.task)}});await ge(e.paths,g);let w=await L(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await XC({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks}),h=await Nu({paths:e.paths,name:e.name,trigger:"v2-integrate"}),m=h.state;return{state:m,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:U(m)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=nw().captureExecutionIdentity({identityProvider:ut,executionRef:PT("builder")}),m=await Cx({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(m)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await L(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==ut){let S=await tc({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:S,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(S)}}Yu(v);let m=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:S})=>S==="passed")?v.verification.checks:null)??(await Tx({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,g=PT("verifier"),w=await jx({paths:e.paths,name:e.name,checks:m,verifierExecutionId:g,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:w,checks:m,requestChecks:null,verifierDispatch:xT({paths:e.paths,state:w,checks:m,verifierExecutionRef:g,supervisor:a?n:null}),continuation:U(w)}}if(t.kind==="verifier-execution-error"){let v=await L(e.paths,e.name);Yu(v),await DN({paths:e.paths,state:v});let h=await Ox({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:U(h)}}if(t.kind==="verifier-unavailable"){let v=await Hx({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:U(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await L(e.paths,e.name),c=Yu(s),l=await DN({paths:e.paths,state:s}),u=nw(),d=u.captureExecutionIdentity({identityProvider:ut,executionRef:l}),f=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await ee(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");f=fu(v)}let p=await $x({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:d,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&p.response.kind==="final-result"){if(p.state.verification_result==="pass"&&(p.checks.length===0||p.checks.some(({status:m})=>m!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=f??await ee(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let h=hu(v,p.state);return await ge(e.paths,h),{...p,supervisorState:h,verifierDispatch:null,continuation:U(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:xT({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await DN({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:U(p.state)}}vo();hn();us();var mU=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function vU(e){let t=Re(e,"--expected-state-version"),r=Re(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new H("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new H("--expected-state-version must be a positive integer");if(!mU.has(r))throw new H("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Pn(e,t){let r=await vt({paths:e,state:t}),n=(r?.confirmed?await ee(e,t.name,{diagnostics:!0}):null)?.children.flatMap(({task:a})=>a?[a.child]:[])??[];return{...r?{childSummary:r.children.reduce((a,o)=>({...a,[o.status]:(a[o.status]??0)+1}),{total:r.children.length}),readyChildren:n.length>0?n:r.readyChildren}:{},continuation:U(t,r)}}function gU(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function TT(e){return{action:e.action,reason:e.reason,message:e.message}}async function jT(e,t){let r=Qe(e,"change name"),i=Re(e,"--summary"),n=Re(e,"--runner-input"),a=It(e,"--confirmed"),o=It(e,"--accept-result"),s=It(e,"--revise-implementation"),c=It(e,"--revise-requirements"),l=It(e,"--retry-verifier"),u=It(e,"--resolve-verifier-blocker"),d=Re(e,"--coordination-mode"),f=d;if(d!==void 0&&!_f.includes(d))throw new H("--coordination-mode must be multi-session or single-session");let p=Re(e,"--max-parallel"),v=p===void 0?2:Number(p);if(!Number.isSafeInteger(v)||v<1)throw new H("--max-parallel must be a positive integer");let h=vU(e);if([a,o,s,c,l,u].filter(Boolean).length>1)throw new H("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(f!==void 0&&(a||o||s||c||l||u||n!==void 0))throw new H("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");Ce(e);let m=await xr(t);if(!await _e(m.paths,r)){if(n)throw new H("--runner-input is only valid for portable Native changes");if(!i)throw new H("--summary is required");let b=await mi({paths:m.paths,name:r});return W("next",{state:Vt(b,m.paths),migration:{completed:!0,summary:i},continuation:U(b)})}let g=await L(m.paths,r),w=gy(m.paths,g);if(w){let b=U(g),k=g.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return W("next",{state:Vt(g,m.paths),...await Pn(m.paths,g),recovery:{action:"await-user",reason:"workspace-mismatch",message:w},continuation:{...b,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...b.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${w}. ${k}`,suggestedReply:null,agentInstruction:k}}})}if(n){if(i||a||o||s||c||l||u||f!==void 0||h)throw new H("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let b=await ny({paths:m.paths,name:r});if(b.action==="rerun-final-verification")return W("next",{state:Vt(b.state,m.paths),...await Pn(m.paths,b.state)});let k=await jo({paths:m.paths,name:r,preserveRunningExecution:!0}),R=k.state;if(k.action==="await-user"||k.action==="done"||k.reason!=="available")return W("next",{state:Vt(R,m.paths),recovery:TT(k),...await Pn(m.paths,R)});if(R.phase==="build"){let Ne=await Ao({paths:m.paths,state:R});if(Ne.drifted){let Ue=await rc({paths:m.paths,name:r,reason:Ne.reason??"Native confirmed requirements changed"});return W("next",{state:Vt(Ue,m.paths),...await Pn(m.paths,Ue)})}let oe=await ee(m.paths,r),ce=await vt({paths:m.paths,state:R});if(ce&&!ce.allDone&&!oe)throw new H("Native parent Build advances child changes and does not accept a Builder handoff")}let I=await _T(n,t),C=await IT({paths:m.paths,name:r,input:I,maxVerifyFailures:m.config.native.max_verify_failures});return W("next",{...gU(C),state:Vt(C.state,m.paths),...await Pn(m.paths,C.state),coordination:ut})}let S=await ny({paths:m.paths,name:r});if(S.action==="rerun-final-verification")return W("next",{state:Vt(S.state,m.paths),...await Pn(m.paths,S.state)});let N=await jo({paths:m.paths,name:r}),y=N.state;if(f!==void 0&&y.phase!=="shape")throw new H("--coordination-mode is only valid when confirming Shape");if(!i)throw new H("--summary is required");let E,P=null;if(a)if(y.phase==="shape"&&y.status==="await-user"&&y.loop.next_action==="confirm-shape"){if(!h)throw new H("--expected-state-version and --expected-action are required for Shape confirmation");E=await Px({paths:m.paths,name:r,expectedContinuation:h})}else{if(y.phase==="shape")throw new H("--confirmed is only valid from the persisted Shape user confirmation boundary");if(y.phase==="verify"&&y.status==="await-user"&&y.loop.next_action==="confirm-verifier-unavailable")E=await Bx({paths:m.paths,name:r,summary:i,expectedContinuation:h});else throw new H("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!h&&(y.phase!=="verify"||y.status!=="await-user"||y.loop.next_action!=="confirm-skill-coordinated-pass"))throw new H("--accept-result is only valid for a pending Verify pass decision");E=await Dx({paths:m.paths,name:r,expectedContinuation:h})}else if(s){if(y.phase!=="verify")throw new H("--revise-implementation is only valid from Verify");E=await tc({paths:m.paths,name:r,reason:i,expectedContinuation:h})}else if(c){if(!h&&y.phase!=="verify"&&y.phase!=="archive")throw new H("--revise-requirements is only valid from Verify or Archive");E=await rc({paths:m.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:h})}else if(l)E=await Fx({paths:m.paths,name:r,expectedContinuation:h});else if(u)E=await qx({paths:m.paths,name:r,reason:i,expectedContinuation:h});else{if(N.reason!=="available")return W("next",{state:Vt(y,m.paths),recovery:TT(N),...await Pn(m.paths,y)});if(y.phase==="build"){let k=await Ao({paths:m.paths,state:y});if(k.drifted)E=await rc({paths:m.paths,name:r,reason:k.reason??"Native confirmed requirements changed"});else{let R=await vt({paths:m.paths,state:y});if(R){let I=R,C=[],Ne=[],oe=null,ce=await ee(m.paths,r);if(ce&&!R.allDone){let Ue=await UC({paths:m.paths,parent:r,maxParallel:y.coordination_mode==="single-session"?1:v});C=Ue.state.children.flatMap(({task:Ke})=>Ke?[Ke]:[]),oe=Ue.tasks.map(({child:Ke})=>Ke),Ne=Ue.state.children.flatMap(({name:Ke,blocker:jt})=>jt?[{child:Ke,message:jt}]:[]),(C.length>0||Ue.state.stateVersion!==ce.stateVersion)&&(I=await vt({paths:m.paths,state:y})??I)}if(I.allDone&&!(y.loop.stage==="repairing"&&y.verification_result==="fail"))P=await Nu({paths:m.paths,name:r,trigger:"recovery"}),E=P.state;else return W("next",{state:Vt(y,m.paths),childSummary:I.children.reduce((Ue,Ke)=>({...Ue,[Ke.status]:(Ue[Ke.status]??0)+1}),{total:I.children.length}),readyChildren:oe??I.readyChildren,...C.length>0?{supervisorTasks:C}:{},...Ne.length>0?{supervisorBlockers:Ne}:{},continuation:U(y,I)})}}}if(y.phase==="shape"&&(E=await Rx({paths:m.paths,name:r,...f===void 0?{}:{coordinationMode:f},expectedContinuation:h})),E)return W("next",{state:Vt(E,m.paths),...P?{parentAdvance:P.parentAdvance}:{},...await Pn(m.paths,E)});let b=y.phase==="shape"?await vt({paths:m.paths,state:y}):null;return{command:"next",exitCode:65,data:{state:Vt(y,m.paths),continuation:U(y,b)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return W("next",{state:Vt(E,m.paths),...f===void 0?{}:{coordinationMode:f},...await Pn(m.paths,E)})}tt();Q();async function $T(e,t){let r=Qe(e,"root subcommand");if(r==="show"){Ce(e);let i=await X(t);if(!i)throw new Error(".comet/config.yaml was not found");let n=await pe(t,i.native.artifact_root);return W("root show",{projectRoot:t,artifactRoot:i.native.artifact_root,language:i.native.language,nativeRoot:n.nativeRoot,pendingRootMove:i.native.pending_root_move??null})}if(r==="move"){let i=Qe(e,"artifact root");Ce(e);let n=await QI({projectRoot:t,toArtifactRoot:i});return W("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
310
|
+
`)}throw new H(`Unknown root command: ${r}`)}async function OT(e,t){let r=Qe(e,"change name");Ce(e);let{config:i,paths:n}=await xr(t);await Yh(n,r);let a=await _e(n,r)?await Xr({paths:n,name:r}):await Ia(n,r,{clarificationMode:i.native.clarification_mode,maxVerifyFailures:i.native.max_verify_failures});return W("select",{selected:r,continuation:a.continuation},`Selected Native change ${r}
|
|
311
|
+
`)}Ee();Jt();ga();import{promises as HT}from"fs";import DT from"path";Jt();en();Ee();qr();it();Yt();nn();Q();var BT=vi.maxSpecs*4;async function wU(e,t){let r=DT.join(se(e,t),"specs"),i;try{i=await br({root:e.nativeRoot,directory:r,label:"Native proposed specs directory"})}catch(s){if(s.code==="ENOENT")return[];throw s}let n=[],a=0,o=await HT.opendir(r);try{for await(let s of o){if(a+=1,a>BT)throw new Error(`Native proposed specs directory exceeds ${BT} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;uo(s.name);let c=DT.join(r,s.name,"spec.md");await j(e.nativeRoot,c);let l;try{l=await HT.lstat(c)}catch(u){if(u.code==="ENOENT")continue;throw u}if(l.isSymbolicLink()||!l.isFile())throw new Error(`Proposed spec must be a regular file: ${s.name}`);if(n.push(s.name),n.length>vi.maxSpecs)throw new Error("Native proposed specs exceed the spec-count budget")}}finally{await o.close().catch(s=>{if(s.code!=="ERR_DIR_CLOSED")throw s})}return await i.verify(),n.sort()}async function qT(e,t){let r=se(e,t),i={},n=0;for(let a of await wU(e,t)){let o=await re({root:r,ref:`specs/${a}/spec.md`,maxBytes:vi.maxFileBytes});if(n+=o.size,n>vi.maxTotalBytes)throw new Error("Native proposed specs exceed the total byte budget");i[a]=o.text}return i}async function FT(e,t){let r=Qe(e,"change name");Ce(e);let{paths:i}=await xr(t);if(await _e(i,r)){let u=await L(i,r),d=ye(i,r),f=await re({root:d,ref:u.brief,maxBytes:null,includeHash:!1}),p=[];for(let h of u.spec_changes){if(h.source===null)continue;let m=await re({root:d,ref:h.source,maxBytes:null,includeHash:!1});p.push({capability:h.capability,operation:h.operation,source:h.source,content:m.text})}let v={state:u,brief:f.text,proposedSpecs:p,continuation:U(u,await vt({paths:i,state:u}))};return W("show",v)}let n=await Vr(i,r);if(n.status==="migration-required")return W("show",{name:r,schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,migrationRequired:!0,message:n.message});if(n.status!=="current"||!n.state)throw new li(n.schema,n.minimumRuntimeVersion);let a=n.state,o=se(i,r),s=await qT(i,r),c=await re({root:o,ref:a.brief,maxBytes:vi.maxFileBytes}),l={state:a,brief:c.text,proposedSpecs:s};if(Buffer.byteLength(JSON.stringify(l),"utf8")>sI)throw new Error("Native show output exceeds its serialized byte budget");return W("show",l)}import{promises as MT}from"node:fs";import yU from"node:path";async function LT(e,t){let r=Qe(e,"spec subcommand");if(r==="sync"){let s=Re(e,"--input"),c=Qe(e,"change name"),l=Qe(e,"capability");if(Ce(e),!s)throw new H("spec sync requires --input <json-file>");let u=yU.resolve(t,s),d=await MT.lstat(u).catch(()=>{throw new H(`Spec sync input file is unreadable: ${s}`)});if(!d.isFile()||d.isSymbolicLink()||d.size>1024*1024)throw new H("Spec sync input must be a bounded regular JSON file");let f;try{f=JSON.parse(await MT.readFile(u,"utf8"))}catch{throw new H("Spec sync input must contain readable valid JSON")}if(!f||typeof f!="object"||Object.keys(f).sort().join(",")!=="actor,affectedAcceptanceIds,expectedStateVersion,reason,replacements"||typeof f.actor!="string"||typeof f.reason!="string"||!Number.isSafeInteger(f.expectedStateVersion)||!Array.isArray(f.affectedAcceptanceIds)||!f.affectedAcceptanceIds.every(h=>typeof h=="string")||!Array.isArray(f.replacements)||!f.replacements.every(h=>h&&typeof h=="object"&&Object.keys(h).sort().join(",")==="from,to"&&typeof h.from=="string"&&typeof h.to=="string"))throw new H("Spec sync input fields are invalid");let{paths:p}=await xr(t),v=await Mx({...f,paths:p,name:c,capability:l});return W("spec sync",{...v,continuation:U(v)},`Synced Native spec references in ${c}
|
|
312
|
+
`)}if(r!=="remove")throw new H(`Unknown spec command: ${r}`);let i=Qe(e,"change name"),n=Qe(e,"capability");Ce(e);let{paths:a}=await xr(t);await _e(a,i)||await mi({paths:a,name:i});let o=await Lx({paths:a,name:i,capability:n});return W("spec remove",{...o,continuation:U(o)},`Marked Native capability ${n} for removal in ${i}
|
|
313
|
+
`)}zt();ct();Ee();tt();import Cn from"node:path";import{realpathSync as bU}from"node:fs";Q();var FN=Ha(Mn(),1);rn();ct();Jt();oi();import{promises as NU}from"node:fs";import qN from"node:path";var qp=class extends Error{};async function MN(e,t){let r=await re({root:e.nativeRoot,ref:qN.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:4194304,includeHash:!1}),i=(0,FN.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new qp("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:z(i)}}async function WT(e,t){let r;try{r=await NU.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}if(r.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=qN.join(e.archiveDir,n.name,"comet-state.yaml");try{let o=await MN(e,a);o.state.archived&&o.state.status==="done"&&i.push(o)}catch(o){if(o.code==="ENOENT"||o instanceof qp)continue;let s=n.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(s,`Native archive ${n.name} is unreadable: ${o.message}`)}}return i}function Fp(e){return B("comet.native.status-record.v1",e)}function VT(e){let t=qN.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=A(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=z((0,FN.parse)(A(e.projectRoot,["show",`${r}:${t}`])));return Fp(i)===Fp(e.state)?r:null}catch{return null}}function zT(e,t){if(!e.state.archived||e.state.status!=="done"||e.state.name!==t.state.name||e.state.created_at!==t.state.created_at)return!1;let r=VT(e),i=VT(t);if(!r||!i)return!1;try{return A(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function JT(e,t){return e.state.archived&&t.state.archived&&Fp(e.state)===Fp(t.state)}Lr();var kU=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Mp(e,t){let r=Cn.normalize(LN(e)),i=Cn.normalize(LN(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function LN(e){let t=Cn.resolve(e);try{return bU.native(t)}catch{return t}}function SU(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function GT(e){let t=[];for(let r of await NN(e))t.push({name:r,kind:await _e(e,r)?"portable":"legacy"});return t}async function XT(e){let t=Cn.resolve(e),r=kt(e),i=r.length>0?r:[t];i.some(o=>Mp(o,t))||i.push(t);let n=[],a=new Set;for(let o of i.map(s=>Cn.resolve(s)).sort()){let s=Mp(o,t)?t:o,c=LN(s),l=process.platform==="win32"?c.toLowerCase():c;if(a.has(l))continue;a.add(l);let u=await X(s);if(!u)continue;let d=await pe(s,u.native.artifact_root);n.push({projectRoot:s,config:u,paths:d,changes:await GT(d)})}if(n.length===0){let o=await X(e);if(!o)throw new Error(".comet/config.yaml was not found in any registered worktree");let s=await pe(e,o.native.artifact_root);n.push({projectRoot:Cn.resolve(e),config:o,paths:s,changes:await GT(s)})}for(let o of n)o.archiveErrors=[],o.archives=await WT(o.paths,(s,c)=>o.archiveErrors.push({name:s,message:c}));return n}function UT(e,t){return e.workspace.bindingState==="aligned"?0:Mp(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function QT(e,t){let r=new Map;for(let n of t){for(let a of n.changes)r.set(a.name,[...r.get(a.name)??[],{source:n,kind:a.kind}]);for(let a of n.archives??[])r.has(a.state.name)||r.set(a.state.name,[]);for(let a of n.archiveErrors??[])r.has(a.name)||r.set(a.name,[])}let i=[];for(let[n,a]of[...r.entries()].sort(([o],[s])=>o.localeCompare(s))){let o=await Promise.all(a.map(async({source:u,kind:d})=>{if(d==="portable")try{let f=await Xr({paths:u.paths,name:n});return{source:u,name:n,kind:d,workspace:f.workspace,portableStatus:f,inspectionError:null}}catch(f){return{source:u,name:n,kind:d,workspace:await $l(u.paths,n),portableStatus:null,inspectionError:f instanceof Error?f.message:String(f)}}return{source:u,name:n,kind:d,workspace:await $l(u.paths,n),portableStatus:null,inspectionError:null}})),s=t.flatMap(u=>(u.archives??[]).filter(({state:d})=>d.name===n).map(d=>{let f=IN({paths:u.paths,...d});return{source:u,name:n,kind:"portable",workspace:f.workspace,portableStatus:f,inspectionError:null,record:d}})),c=t.flatMap(u=>(u.archiveErrors??[]).filter(d=>d.name===n).map(d=>({source:u,error:d})))[0];if(c){i.push({source:c.source,name:n,kind:"portable",portableStatus:null,inspectionError:c.error.message,workspace:{projectRoot:c.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:c.error.message}});continue}if(s.length>0){for(let d of o)if(d.kind==="portable")try{d.record=await MN(d.source.paths,Cn.join(d.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let u=s.find(d=>[...o,...s.filter(f=>!JT(d.record,f.record))].every(f=>f.record&&zT(d.record,f.record)));if(u){i.push(u);continue}i.push({...s[0],inspectionError:`Native change ${n} has conflicting active/archive records; identity and committed Git ancestry do not prove supersession. Resolve the records explicitly.`});continue}o.sort((u,d)=>UT(u,e)-UT(d,e)||u.source.projectRoot.localeCompare(d.source.projectRoot));let l=o.filter(u=>u.workspace.bindingState==="aligned");l.length>1?i.push(...l):l.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(l[0]??o[0])}if(i.length>Ar.maxChanges)throw new Error(`Native status discovery exceeds ${Ar.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function KT(e,t){let r=t.toString(36),i=B("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function EU(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=kU.exec(e.cursor);if(!t||t[1]!==e.candidatesHash)throw new Error("Native workspace status cursor is invalid or stale");let r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native workspace status cursor offset is invalid");let i=B("comet.native.workspace-status-cursor.v1",{candidatesHash:e.candidatesHash,offset:r});if(t[3]!==i)throw new Error("Native workspace status cursor integrity failed");return r}function YT(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?SU(r):null,nextPageArgs:r}}async function RU(e,t,r){let i=null;try{i=await fo(e.source.paths,e.name)}catch{}return i?.state?{schema:"comet.native.status.v2",name:e.name,phase:i.state.phase,status:"blocked",migrationRequired:!0,legacySchema:i.schema,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:i.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:Ia(e.source.paths,e.name,{details:t,...r?{acceptanceCursor:r}:{},clarificationMode:e.source.config.native.clarification_mode,maxVerifyFailures:e.source.config.native.max_verify_failures})}async function ZT(e,t,r,i){if(e.inspectionError)return{schema:"comet.native.status.v2",name:e.name,phase:"invalid",status:"blocked",inspectionError:e.inspectionError,workspace:e.workspace,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:"invalid",status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}};if(e.kind==="portable"){if(r)throw new Error("Portable Native status includes the complete acceptance list");return!t&&e.portableStatus?e.portableStatus:e.record?.state.archived?IN({paths:e.source.paths,...e.record,details:t,cursor:i}):Xr({paths:e.source.paths,name:e.name,details:t,...i?{cursor:i}:{}})}return RU(e,t,r)}async function ej(e){let t=await XT(e.projectRoot),r=(await QT(e.projectRoot,t)).filter(i=>i.name===e.name);if(r.length===0){let i=t.find(n=>Mp(n.projectRoot,e.projectRoot))??t[0];return Ia(i.paths,e.name,{details:e.details,...e.acceptanceCursor?{acceptanceCursor:e.acceptanceCursor}:{},clarificationMode:i.config.native.clarification_mode,maxVerifyFailures:i.config.native.max_verify_failures})}if(r.length>1)throw new Error(`Native change ${e.name} has multiple aligned workspace bindings: ${r.map(i=>i.source.projectRoot).join(", ")}`);return ZT(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function tj(e){let t=await XT(e.projectRoot),r=await QT(e.projectRoot,t),i=B("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=EU({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+Ar.maxItems).map(u=>ZT(u,!1))),o=[],s=r.some(({kind:u})=>u==="portable")?"comet.native.status-page.v2":"comet.native.status-page.v1";for(let u of a){let d=[...o,u],f=n+d.length,p=f<r.length?KT(i,f):null,v={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...YT(Cn.resolve(e.projectRoot),p),limits:{...Ar}};if(Buffer.byteLength(JSON.stringify(v),"utf8")>Ar.maxSerializedBytes){if(o.length===0)throw new Error("Native workspace status item exceeds its page serialization budget");break}o.push(u)}let c=n+o.length,l=c<r.length?KT(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...YT(Cn.resolve(e.projectRoot),l),limits:{...Ar}}}async function rj(e,t){let r=It(e,"--details"),i=Re(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new H("status --details requires a change name");if(i&&n&&!r)throw new H("--cursor for a named status requires --details");Ce(e);let a=n?await ej({projectRoot:t,name:n,details:r,...i?{detailsCursor:i}:{}}):await tj({projectRoot:t,...i?{cursor:i}:{}});return W("status",a)}var PU={"hook-guard":bT,init:kT,root:$T,new:ST,spec:LT,show:FT,status:rj,select:OT,next:jT,archive:hI,check:NI,doctor:TN};async function CU(e,t){let r=e.indexOf("--help");if(e.length===0||r>=0||e[0]==="help"){let o=e[0]==="help"?e.slice(1):r>=0?e.slice(0,r):[],s;try{s=hN(o)}catch(c){throw new H(c.message)}return{command:s.topic?`${s.topic} --help`:"help",exitCode:0,data:s,text:s.usage}}let i=e.shift(),n=await cI(t),a=PU[i];if(!a)throw new H(`Unknown Native command: ${i}`);return a(e,n)}async function ij(e){let t=[...e],r=t.indexOf("--"),i=r<0?t:t.slice(0,r),n=r<0?[]:t.slice(r),a=i.includes("--json"),o=i.includes("--verbose"),s,c=i[0]??null;try{It(i,"--json"),It(i,"--verbose"),s=Re(i,"--project-root");let l=[...i,...n];return c=l[0]??null,mN(await CU(l,s),a,o)}catch(l){return mN(dI(c,l),a,o)}}async function AU(e=process.argv.slice(2)){let t=await ij(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
|
|
314
314
|
`)?"":`
|
|
315
315
|
`)),t.exitCode}var nj=process.argv[1];nj&&import.meta.url===xU(nj).href&&AU().then(e=>{process.exitCode=e});export{AU as main};
|