@rpamis/comet 0.4.2 → 0.4.3
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 -332
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-check.mjs +89 -89
- package/assets/skills/comet/scripts/comet-guard.mjs +102 -102
- package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
- package/assets/skills/comet/scripts/comet-runtime.mjs +227 -227
- package/assets/skills/comet/scripts/comet-state.mjs +124 -124
- package/assets/skills/comet-classic/SKILL.md +2 -0
- package/assets/skills/comet-classic/reference/scripts.md +8 -0
- package/assets/skills/comet-hotfix/SKILL.md +1 -0
- package/assets/skills/comet-native/SKILL.md +3 -1
- package/assets/skills/comet-native/reference/commands.md +10 -0
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +13 -13
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +26 -26
- package/assets/skills/comet-tweak/SKILL.md +1 -0
- package/assets/skills-zh/comet-classic/SKILL.md +2 -0
- package/assets/skills-zh/comet-classic/reference/scripts.md +2 -0
- package/assets/skills-zh/comet-hotfix/SKILL.md +1 -0
- package/assets/skills-zh/comet-native/SKILL.md +3 -1
- package/assets/skills-zh/comet-native/reference/commands.md +10 -0
- package/assets/skills-zh/comet-tweak/SKILL.md +1 -0
- package/bin/comet-daemon-router.js +35 -7
- package/dist/app/commands/daemon-server.d.ts.map +1 -1
- package/dist/app/commands/daemon-server.js +1 -0
- package/dist/app/commands/daemon-server.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +0 -1
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts +2 -0
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js +22 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.js +8 -6
- package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
- package/dist/domains/project-knowledge/corpus.d.ts +5 -0
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +34 -9
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/project-knowledge/index-store.d.ts +5 -2
- package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index-store.js +95 -52
- package/dist/domains/project-knowledge/index-store.js.map +1 -1
- package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-provider.js +14 -3
- package/dist/domains/project-knowledge/local-provider.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +2 -2
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +2 -2
- package/dist/domains/project-knowledge/local-store.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +5 -4
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/project-knowledge/provider-factory.d.ts.map +1 -1
- package/dist/domains/project-knowledge/provider-factory.js +7 -5
- package/dist/domains/project-knowledge/provider-factory.js.map +1 -1
- package/dist/domains/project-knowledge/types.d.ts +1 -0
- package/dist/domains/project-knowledge/types.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +31 -3
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/platform/process/comet-daemon.d.ts.map +1 -1
- package/dist/platform/process/comet-daemon.js +1 -0
- package/dist/platform/process/comet-daemon.js.map +1 -1
- package/dist/platform/process/windows-process-broker.d.ts +12 -0
- package/dist/platform/process/windows-process-broker.d.ts.map +1 -0
- package/dist/platform/process/windows-process-broker.js +91 -0
- package/dist/platform/process/windows-process-broker.js.map +1 -0
- package/package.json +1 -1
|
@@ -200,7 +200,7 @@ ${l.body??""}`).join(`
|
|
|
200
200
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
201
201
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
202
202
|
# 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
203
|
-
# 可选值:neutral | strict`}}});import{constants as lh,promises as Oo}from"fs";function Ny(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ex(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function xu(e){return{dev:e.dev,ino:e.ino,birthtime:Ny(e)}}function uh(e,t){let r=xu(e),i=xu(t);return Tr(r,i)?ne(r,i):ne(r,i)&&Ny(e)===Ny(t)&&Ex(e)===Ex(t)&&e.size===t.size}async function Do(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 Oo.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new xi("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new xi("too-large",`${i} exceeds ${t} bytes`);let o=await Oo.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:xu(a)});let s=process.platform==="win32"?lh.O_RDONLY:lh.O_RDONLY|lh.O_NOFOLLOW|lh.O_NONBLOCK,c;try{c=await Oo.open(e,s)}catch(l){throw l.code==="ELOOP"?new xi("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Oo.lstat(e,{bigint:n}),Oo.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!uh(a,l)||!uh(a,u))throw new xi("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:xu(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:k}=await c.read(h,0,Math.min(h.length,w),null);if(k===0)break;if(p+=k,p>t)throw new xi("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(h.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[m,v,g]=await Promise.all([c.stat({bigint:n}),Oo.lstat(e,{bigint:n}),Oo.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!uh(a,m)||!uh(a,v))throw new xi("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:xu(m)}),{bytes:Buffer.concat(f,p),stat:m,realPath:g}}finally{await c.close()}}var xi,Cu=W(()=>{"use strict";ql();xi=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as dh}from"fs";import _a from"path";function uB(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function by(e,t){let r=_a.relative(e,t);return r===""||!_a.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_a.sep}`)}async function Rx(e,t){let r=_a.resolve(e),i=await dh.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return dh.realpath(r)}async function Px(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=_a.join(n,r[a]);let o;try{o=await dh.lstat(n)}catch(u){if(uB(u))return{exists:!1,kind:"missing"};throw u}let s=_a.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 dh.realpath(n);if(!by(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 Cn(e,t,r){let i=oh(t,r.label),n=_a.resolve(e),a=await Rx(n,r.label),o=i.split("/"),s=_a.resolve(n,...o);if(!by(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Px(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Wt(e,t,r,i){let n=await Cn(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 Rx(n.projectRoot,i.label);return Do(n.target,r,{...i,verify:async(o,s)=>{if(!by(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Px(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var _n=W(()=>{"use strict";Cu();Ca()});import{createHash as dB}from"crypto";function ky(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function fB(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fh(e,t={}){return(await Au(e,t)).document}async function xx(e){try{return(await Wt(e,_u,Eu,{label:_u})).bytes}catch(t){if(fB(t))return null;throw t}}function Cx(e){return e?{exists:!0,sha256:dB("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ph(e){return Cx(await xx(e))}async function Au(e,t={}){let r=await xx(e);return{document:r?Zs(r.toString("utf8"),t):null,identity:Cx(r)}}async function Ho(e){return(await fh(e))?.config??null}var _u,Fo=W(()=>{"use strict";Ca();_n();_u=".comet/config.yaml"});import{randomUUID as pB}from"crypto";import{constants as hB,promises as ir}from"fs";import Ci from"path";async function Sy(e,t){try{return await Kf(e,t),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await ir.copyFile(e,t,hB.COPYFILE_EXCL),{linked:!1}}function hh(e,t){let r=Ci.relative(e,t);return r===""||!Ci.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ci.sep}`)}function mh(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function mB(e,t){return ne(e,mh(t))}function vh(e,t){return ne(mh(e),mh(t))}function vB(e,t){return vh(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function _x(e){let t=await ir.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 ir.realpath(e),...mh(t)}}async function ec(e){for(let t of e){let r=await ir.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!mB(t,r)||await ir.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function gB(e,t,r){let[i,n]=await Promise.all([ir.lstat(e),ir.realpath(e),ec(r)]);if(!i.isFile()||i.isSymbolicLink()||!vh(i,t)||!hh(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function wB(e,t){let r=Ci.resolve(e),i=Ci.resolve(t);if(!hh(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await _x(r)],a=Ci.relative(r,i).split(Ci.sep).filter(Boolean),o=r;for(let s of a){await ec(n),o=Ci.join(o,s);try{await ir.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await _x(o);if(!hh(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ec(n),n}async function yB(e){let t;try{t=await ir.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 NB(e,t,r){let i=Ci.dirname(e),n=await wB(r.containedRoot,i),a=Ci.join(i,`.${Ci.basename(e)}.${pB()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await ir.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([ir.lstat(a),ir.realpath(a)]);if(await ec(n),!l.isFile()||l.isSymbolicLink()||!vh(s,l)||!hh(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(),!vh(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 gB(a,c,n),await r.beforeCommit?.(),await ec(n);let d=await ir.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!vB(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Sy(a,e),await ir.unlink(a)):await Gf(a,e),await yB(i)}catch(l){await o?.close();try{await ec(n),await ir.rm(a,{force:!0})}catch{}throw l}}async function qo(e,t,r){await NB(e,t,r)}var tc=W(()=>{"use strict";kg();ql()});var BX,Ey=W(()=>{"use strict";tc();Fo();_n();BX=16*1024});async function Ry(e,t){if(!t)return;let r=await ph(e);if(!ky(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Py=W(()=>{"use strict";tc();Ca();Fo();_n();Ey()});import{existsSync as Ax,promises as Xi}from"fs";import de from"path";import SB from"os";async function xy(e){try{return await Xi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function RB(e){try{let t=await Xi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ic(e,t){let r=de.relative(e,t);return r===""||!de.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${de.sep}`)}async function rc(e){let t=[],r=e;for(;!await xy(r);){let n=de.dirname(r);if(n===r)break;t.push(de.basename(r)),r=n}let i=await Xi.realpath(r);return de.resolve(i,...t.reverse())}async function Cy(e){try{return(await Xi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gh(e){let t=de.resolve(e);try{(await Xi.stat(t)).isDirectory()||(t=de.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=de.resolve(SB.homedir());for(;;){if(!(t===i&&r!==i)){let o=de.join(t,...Iu.split("/")),s=t===r||await RB(o);if(await xy(o)&&s)return t}if(await xy(de.join(t,".git")))return t;let a=de.dirname(t);if(a===t)return r;t=a}}function Aa(e){return $o(e)}async function PB(e,t){let r=Aa(t),i=de.resolve(e,...r.split("/")),n=await Xi.realpath(e),a=await rc(i);if(!ic(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Se(e,t){let r=Aa(t),i=await PB(e,r),n=de.join(i,"comet");if(await Cy(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([rc(i),rc(n)]);if(!ic(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=de.resolve(e),c=de.join(s,".comet","runtime","native");if(await Cy(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Xi.realpath(s),rc(c)]);if(!ic(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:de.join(e,...Iu.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:de.join(n,"specs"),changesDir:de.join(n,"changes"),archiveDir:de.join(n,"archive"),runtimeDir:c,changesRuntimeDir:de.join(c,"changes"),locksDir:de.join(c,"locks"),transactionsDir:de.join(c,"transactions")}}async function wh(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await T(e.nativeRoot,t),await Xi.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await T(e.projectRoot,t),await Xi.mkdir(t,{recursive:!0})}))}function _y(e){if(!EB.test(e))throw new Error(`Invalid Native change name: ${e}`)}function je(e,t){_y(t);let r=de.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Lo(e,t){_y(t);let r=de.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Q(e,t){let r=je(e,t);if(Ax(r))return r;let i=Lo(e,t);return Ax(i)?i:r}function _i(e,t){_y(t);let r=de.join(e.changesDir,t),i=Q(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:de.join(r,"brief.md"),childrenPath:de.join(r,"children.yaml"),specsDir:de.join(r,"specs"),verificationPath:de.join(r,"verification.md"),statePath:de.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:de.join(i,"state.json")}}async function Ix(e){try{let t=await Xi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function ju(e,t){let r=je(e,t),i=Lo(e,t),[n,a]=await Promise.all([Ix(r),Ix(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 Ia(e,t){if(!t.startsWith("runtime/")||de.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=de.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function B(e,t){let r=de.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 ic(de.resolve(e),de.resolve(t))}async function T(e,t){let r=de.resolve(e),i=de.resolve(t);if(!ic(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Cy(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([rc(r),rc(i)]);if(!ic(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Iu,EB,Z=W(()=>{"use strict";Ca();Iu=".comet/config.yaml",EB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import xB from"path";function Mo(e="docs",t="en"){return ch(e,t)}async function te(e){let t=(await fh(e))?.config??null;return t?.native?t:null}async function nc(e){let t=await te(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 Dr(e,t,r={}){let i=await Au(e,{allowPartialProject:!0}),n=Pu(i.document?.value??{},t),a=xB.join(e,...Iu.split("/"));await Ne(a,Ru(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Ry(e,i.identity)}})}async function Tx(e){let t=await gh(e.startPath),r=await te(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Iu} 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?Aa(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??Mo(i??"docs"),a=await Se(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ay,yh,jx,ot=W(()=>{"use strict";Ca();Fo();Py();Oe();Z();Ay=rr,yh=sh,jx=wx});import{spawn as Iy}from"node:child_process";import{existsSync as $x}from"node:fs";import Bo from"node:path";function jy(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function jB(e){let t=(jy(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function TB(e,t,r){let n=Bo.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(jy(t,"PATH")??"").split(Bo.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Bo.win32.extname(e)?[e]:jB(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Bo.join(s,c):Bo.resolve(r,c)))}function ac(e,t,r){return TB(e,t,r).find(i=>$x(i))??e}function $B(e){let t=jy(e,"SystemRoot");if(t){let r=Bo.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if($x(r))return r}return"powershell.exe"}function Tu(e){if(e.some(t=>AB.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function OB(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(IB,"utf16le").toString("base64");return Iy($B(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 Ty(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Iy(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=ac(e,i,r.cwd),a=Bo.win32.extname(n).toLowerCase();return _B.has(a)&&Tu(t),CB.has(a)?OB(n,t,{cwd:r.cwd,env:i}):Iy(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var CB,_B,AB,IB,Nh=W(()=>{"use strict";CB=new Set([".bat",".cmd",".ps1"]),_B=new Set([".bat",".cmd"]),AB=/[&|<>()^%"!\r\n]/u,IB=["$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{execFileSync as DB}from"node:child_process";import Ox from"node:path";function qB(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Qi(e,t,r={}){let i=r.timeoutMs??HB,n=r.maxBufferBytes??FB;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=Ox.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?ac(e,o,a):e,c=Ox.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Tu(t);try{return DB(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 $y(e,t,d,{cause:u,timedOut:qB(u)})}}var HB,FB,$y,bh=W(()=>{"use strict";Nh();HB=6e4,FB=8*1024*1024,$y=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",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Dx}from"node:fs";import Hx from"node:path";function BB(e){let t=Dy.get(e);if(!t)return;let r=t.value===null?MB:LB;if(Date.now()-t.at>r){Dy.delete(e);return}return t.value}async function Hr(e){if(e===process.pid&&Oy!==null)return Oy;let t=BB(e);if(t!==void 0)return t;let r=await VB(e);return e===process.pid&&r!==null&&(Oy=r),e!==process.pid&&Dy.set(e,{value:r,at:Date.now()}),r}async function VB(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Dx.readFile(`/proc/${e}/stat`,"utf8"),Dx.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")return await zB(e);if(process.platform==="darwin"){let t=Qi("/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}function WB(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function zB(e){try{let n=Qi(Hx.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),a=/^CreationDate=(\S+)/mu.exec(n);if(a)return`win32-wmic:${a[1]}`}catch{}let t=process.env.SystemRoot??"C:\\Windows",r=Hx.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Qi(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return WB(i)}function kh(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function oc(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Hr(e);return r===t?"alive":r===null||kh(r)!==kh(t)&&Fx.has(kh(r))&&Fx.has(kh(t))?"unknown":"dead"}async function sc(e,t){return await oc(e,t)!=="dead"}var Oy,LB,MB,Dy,Fx,$u=W(()=>{"use strict";bh();Oy=null,LB=6e4,MB=1e4,Dy=new Map;Fx=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as JB}from"async_hooks";import{randomUUID as Mx}from"crypto";import{promises as ii}from"fs";import Bx from"os";import Xe from"path";function KB(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function UB(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||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Vx(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 Eh(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Tr(r,i)?ne(r,i):ne(r,i)&&e.size===t.size}function Rh(e,t){return Eh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function YB(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&&Rh(e.identity,t.identity)}async function Ai(e){let t,r;try{let i=await Do(e,qx,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof xi?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${qx} 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:UB(JSON.parse(t.toString("utf8")),e),identity:Vx(r)}}async function XB(e){return(await Ai(e))?.owner??null}async function Fy(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Bx.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await oc(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function QB(e,t){try{await ii.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ii.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ph(e,t){let r=await Ai(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Rh(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ii.mkdir(t,{recursive:!0});let i=Xe.join(t,`${Xe.basename(e.file)}.${e.owner.id}.${Mx()}.removed`);try{await ii.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ai(i);if(!n||n.owner.id!==e.owner.id||!Eh(n.identity,e.identity))throw await QB(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ii.rm(i,{force:!0}),"removed"}async function Wx(e){let t=await Hr(process.pid);return{id:Mx(),pid:process.pid,hostname:Bx.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function zx(e,t){let r;try{r=await ii.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await XB(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)+`
|
|
203
|
+
# 可选值:neutral | strict`}}});import{constants as lh,promises as Oo}from"fs";function Ny(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ex(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function xu(e){return{dev:e.dev,ino:e.ino,birthtime:Ny(e)}}function uh(e,t){let r=xu(e),i=xu(t);return Tr(r,i)?ne(r,i):ne(r,i)&&Ny(e)===Ny(t)&&Ex(e)===Ex(t)&&e.size===t.size}async function Do(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 Oo.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new xi("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new xi("too-large",`${i} exceeds ${t} bytes`);let o=await Oo.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:xu(a)});let s=process.platform==="win32"?lh.O_RDONLY:lh.O_RDONLY|lh.O_NOFOLLOW|lh.O_NONBLOCK,c;try{c=await Oo.open(e,s)}catch(l){throw l.code==="ELOOP"?new xi("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Oo.lstat(e,{bigint:n}),Oo.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!uh(a,l)||!uh(a,u))throw new xi("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:xu(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:k}=await c.read(h,0,Math.min(h.length,w),null);if(k===0)break;if(p+=k,p>t)throw new xi("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(h.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[m,v,g]=await Promise.all([c.stat({bigint:n}),Oo.lstat(e,{bigint:n}),Oo.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!uh(a,m)||!uh(a,v))throw new xi("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:xu(m)}),{bytes:Buffer.concat(f,p),stat:m,realPath:g}}finally{await c.close()}}var xi,Cu=W(()=>{"use strict";ql();xi=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as dh}from"fs";import _a from"path";function uB(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function by(e,t){let r=_a.relative(e,t);return r===""||!_a.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_a.sep}`)}async function Rx(e,t){let r=_a.resolve(e),i=await dh.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return dh.realpath(r)}async function Px(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=_a.join(n,r[a]);let o;try{o=await dh.lstat(n)}catch(u){if(uB(u))return{exists:!1,kind:"missing"};throw u}let s=_a.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 dh.realpath(n);if(!by(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 Cn(e,t,r){let i=oh(t,r.label),n=_a.resolve(e),a=await Rx(n,r.label),o=i.split("/"),s=_a.resolve(n,...o);if(!by(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Px(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Wt(e,t,r,i){let n=await Cn(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 Rx(n.projectRoot,i.label);return Do(n.target,r,{...i,verify:async(o,s)=>{if(!by(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Px(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var _n=W(()=>{"use strict";Cu();Ca()});import{createHash as dB}from"crypto";function ky(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function fB(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function fh(e,t={}){return(await Au(e,t)).document}async function xx(e){try{return(await Wt(e,_u,Eu,{label:_u})).bytes}catch(t){if(fB(t))return null;throw t}}function Cx(e){return e?{exists:!0,sha256:dB("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ph(e){return Cx(await xx(e))}async function Au(e,t={}){let r=await xx(e);return{document:r?Zs(r.toString("utf8"),t):null,identity:Cx(r)}}async function Ho(e){return(await fh(e))?.config??null}var _u,Fo=W(()=>{"use strict";Ca();_n();_u=".comet/config.yaml"});import{randomUUID as pB}from"crypto";import{constants as hB,promises as ir}from"fs";import Ci from"path";async function Sy(e,t){try{return await Kf(e,t),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await ir.copyFile(e,t,hB.COPYFILE_EXCL),{linked:!1}}function hh(e,t){let r=Ci.relative(e,t);return r===""||!Ci.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ci.sep}`)}function mh(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function mB(e,t){return ne(e,mh(t))}function vh(e,t){return ne(mh(e),mh(t))}function vB(e,t){return vh(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function _x(e){let t=await ir.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 ir.realpath(e),...mh(t)}}async function ec(e){for(let t of e){let r=await ir.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!mB(t,r)||await ir.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function gB(e,t,r){let[i,n]=await Promise.all([ir.lstat(e),ir.realpath(e),ec(r)]);if(!i.isFile()||i.isSymbolicLink()||!vh(i,t)||!hh(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function wB(e,t){let r=Ci.resolve(e),i=Ci.resolve(t);if(!hh(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let n=[await _x(r)],a=Ci.relative(r,i).split(Ci.sep).filter(Boolean),o=r;for(let s of a){await ec(n),o=Ci.join(o,s);try{await ir.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await _x(o);if(!hh(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ec(n),n}async function yB(e){let t;try{t=await ir.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 NB(e,t,r){let i=Ci.dirname(e),n=await wB(r.containedRoot,i),a=Ci.join(i,`.${Ci.basename(e)}.${pB()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await ir.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([ir.lstat(a),ir.realpath(a)]);if(await ec(n),!l.isFile()||l.isSymbolicLink()||!vh(s,l)||!hh(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(),!vh(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 gB(a,c,n),await r.beforeCommit?.(),await ec(n);let d=await ir.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!vB(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Sy(a,e),await ir.unlink(a)):await Gf(a,e),await yB(i)}catch(l){await o?.close();try{await ec(n),await ir.rm(a,{force:!0})}catch{}throw l}}async function qo(e,t,r){await NB(e,t,r)}var tc=W(()=>{"use strict";kg();ql()});var VX,Ey=W(()=>{"use strict";tc();Fo();_n();VX=16*1024});async function Ry(e,t){if(!t)return;let r=await ph(e);if(!ky(r,t))throw new Error("Project config changed before commit; rerun the operation")}var Py=W(()=>{"use strict";tc();Ca();Fo();_n();Ey()});import{existsSync as Ax,promises as Xi}from"fs";import de from"path";import SB from"os";async function xy(e){try{return await Xi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function RB(e){try{let t=await Xi.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ic(e,t){let r=de.relative(e,t);return r===""||!de.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${de.sep}`)}async function rc(e){let t=[],r=e;for(;!await xy(r);){let n=de.dirname(r);if(n===r)break;t.push(de.basename(r)),r=n}let i=await Xi.realpath(r);return de.resolve(i,...t.reverse())}async function Cy(e){try{return(await Xi.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gh(e){let t=de.resolve(e);try{(await Xi.stat(t)).isDirectory()||(t=de.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=de.resolve(SB.homedir());for(;;){if(!(t===i&&r!==i)){let o=de.join(t,...Iu.split("/")),s=t===r||await RB(o);if(await xy(o)&&s)return t}if(await xy(de.join(t,".git")))return t;let a=de.dirname(t);if(a===t)return r;t=a}}function Aa(e){return $o(e)}async function PB(e,t){let r=Aa(t),i=de.resolve(e,...r.split("/")),n=await Xi.realpath(e),a=await rc(i);if(!ic(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Se(e,t){let r=Aa(t),i=await PB(e,r),n=de.join(i,"comet");if(await Cy(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([rc(i),rc(n)]);if(!ic(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=de.resolve(e),c=de.join(s,".comet","runtime","native");if(await Cy(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Xi.realpath(s),rc(c)]);if(!ic(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:de.join(e,...Iu.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:de.join(n,"specs"),changesDir:de.join(n,"changes"),archiveDir:de.join(n,"archive"),runtimeDir:c,changesRuntimeDir:de.join(c,"changes"),locksDir:de.join(c,"locks"),transactionsDir:de.join(c,"transactions")}}async function wh(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await T(e.nativeRoot,t),await Xi.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await T(e.projectRoot,t),await Xi.mkdir(t,{recursive:!0})}))}function _y(e){if(!EB.test(e))throw new Error(`Invalid Native change name: ${e}`)}function je(e,t){_y(t);let r=de.join(e.changesRuntimeDir,t);if(!q(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Lo(e,t){_y(t);let r=de.join(e.changesDir,t,"runtime");if(!q(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Q(e,t){let r=je(e,t);if(Ax(r))return r;let i=Lo(e,t);return Ax(i)?i:r}function _i(e,t){_y(t);let r=de.join(e.changesDir,t),i=Q(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:de.join(r,"brief.md"),childrenPath:de.join(r,"children.yaml"),specsDir:de.join(r,"specs"),verificationPath:de.join(r,"verification.md"),statePath:de.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:de.join(i,"state.json")}}async function Ix(e){try{let t=await Xi.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function ju(e,t){let r=je(e,t),i=Lo(e,t),[n,a]=await Promise.all([Ix(r),Ix(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 Ia(e,t){if(!t.startsWith("runtime/")||de.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=de.resolve(e,...t.slice(8).split("/"));if(!q(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function B(e,t){let r=de.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 ic(de.resolve(e),de.resolve(t))}async function T(e,t){let r=de.resolve(e),i=de.resolve(t);if(!ic(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Cy(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([rc(r),rc(i)]);if(!ic(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Iu,EB,Z=W(()=>{"use strict";Ca();Iu=".comet/config.yaml",EB=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import xB from"path";function Mo(e="docs",t="en"){return ch(e,t)}async function te(e){let t=(await fh(e))?.config??null;return t?.native?t:null}async function nc(e){let t=await te(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 Dr(e,t,r={}){let i=await Au(e,{allowPartialProject:!0}),n=Pu(i.document?.value??{},t),a=xB.join(e,...Iu.split("/"));await Ne(a,Ru(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Ry(e,i.identity)}})}async function Tx(e){let t=await gh(e.startPath),r=await te(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Iu} 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?Aa(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??Mo(i??"docs"),a=await Se(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ay,yh,jx,ot=W(()=>{"use strict";Ca();Fo();Py();Oe();Z();Ay=rr,yh=sh,jx=wx});import{spawn as Iy}from"node:child_process";import{existsSync as $x}from"node:fs";import Bo from"node:path";function jy(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function jB(e){let t=(jy(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function TB(e,t,r){let n=Bo.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(jy(t,"PATH")??"").split(Bo.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Bo.win32.extname(e)?[e]:jB(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Bo.join(s,c):Bo.resolve(r,c)))}function ac(e,t,r){return TB(e,t,r).find(i=>$x(i))??e}function $B(e){let t=jy(e,"SystemRoot");if(t){let r=Bo.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if($x(r))return r}return"powershell.exe"}function Tu(e){if(e.some(t=>AB.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function OB(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(IB,"utf16le").toString("base64");return Iy($B(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 Ty(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Iy(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=ac(e,i,r.cwd),a=Bo.win32.extname(n).toLowerCase();return _B.has(a)&&Tu(t),CB.has(a)?OB(n,t,{cwd:r.cwd,env:i}):Iy(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var CB,_B,AB,IB,Nh=W(()=>{"use strict";CB=new Set([".bat",".cmd",".ps1"]),_B=new Set([".bat",".cmd"]),AB=/[&|<>()^%"!\r\n]/u,IB=["$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{execFileSync as DB}from"node:child_process";import Ox from"node:path";function qB(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function Qi(e,t,r={}){let i=r.timeoutMs??HB,n=r.maxBufferBytes??FB;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=Ox.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?ac(e,o,a):e,c=Ox.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Tu(t);try{return DB(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 $y(e,t,d,{cause:u,timedOut:qB(u)})}}var HB,FB,$y,bh=W(()=>{"use strict";Nh();HB=6e4,FB=8*1024*1024,$y=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",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Dx}from"node:fs";import Hx from"node:path";function BB(e){let t=Dy.get(e);if(!t)return;let r=t.value===null?MB:LB;if(Date.now()-t.at>r){Dy.delete(e);return}return t.value}async function Hr(e){if(e===process.pid&&Oy!==null)return Oy;let t=BB(e);if(t!==void 0)return t;let r=await VB(e);return e===process.pid&&r!==null&&(Oy=r),e!==process.pid&&Dy.set(e,{value:r,at:Date.now()}),r}async function VB(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Dx.readFile(`/proc/${e}/stat`,"utf8"),Dx.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")return await zB(e);if(process.platform==="darwin"){let t=Qi("/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}function WB(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function zB(e){try{let n=Qi(Hx.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),a=/^CreationDate=(\S+)/mu.exec(n);if(a)return`win32-wmic:${a[1]}`}catch{}let t=process.env.SystemRoot??"C:\\Windows",r=Hx.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=Qi(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return WB(i)}function kh(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function oc(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Hr(e);return r===t?"alive":r===null||kh(r)!==kh(t)&&Fx.has(kh(r))&&Fx.has(kh(t))?"unknown":"dead"}async function sc(e,t){return await oc(e,t)!=="dead"}var Oy,LB,MB,Dy,Fx,$u=W(()=>{"use strict";bh();Oy=null,LB=6e4,MB=1e4,Dy=new Map;Fx=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as JB}from"async_hooks";import{randomUUID as Mx}from"crypto";import{promises as ii}from"fs";import Bx from"os";import Xe from"path";function KB(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function UB(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||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Vx(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 Eh(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Tr(r,i)?ne(r,i):ne(r,i)&&e.size===t.size}function Rh(e,t){return Eh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function YB(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&&Rh(e.identity,t.identity)}async function Ai(e){let t,r;try{let i=await Do(e,qx,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof xi?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${qx} 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:UB(JSON.parse(t.toString("utf8")),e),identity:Vx(r)}}async function XB(e){return(await Ai(e))?.owner??null}async function Fy(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Bx.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await oc(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function QB(e,t){try{await ii.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ii.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ph(e,t){let r=await Ai(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Rh(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ii.mkdir(t,{recursive:!0});let i=Xe.join(t,`${Xe.basename(e.file)}.${e.owner.id}.${Mx()}.removed`);try{await ii.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ai(i);if(!n||n.owner.id!==e.owner.id||!Eh(n.identity,e.identity))throw await QB(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ii.rm(i,{force:!0}),"removed"}async function Wx(e){let t=await Hr(process.pid);return{id:Mx(),pid:process.pid,hostname:Bx.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function zx(e,t){let r;try{r=await ii.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await XB(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)+`
|
|
204
204
|
`,"utf8"),await r.sync(),i=Vx(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ai(e);if(!i||!n||n.owner.id!==t.id||!Eh(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function ZB(e,t){let r=await T(e.runtimeDir,e.locksDir);await ii.mkdir(r,{recursive:!0});let i=await T(e.runtimeDir,Xe.join(r,Hy));await ii.mkdir(i,{recursive:!0});let n=await Wx(t),a=Xe.join(i,`.${n.id}.tmp`),o=Xe.join(i,`${n.id}.claim`);try{let s=await zx(a,n);await ii.rename(a,o);let c=await Ai(o);if(!c||!Eh(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 ii.rm(a,{force:!0})}}async function eV(e){let t=Xe.dirname(e.file),r=!1,i=Xe.basename(e.file);for(let n of await ii.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Xe.join(t,n.name);if(Xe.resolve(a)!==Xe.resolve(e.file))try{let o=await Ai(a),s=await Fy(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ph(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Jx(e){let t=await Ai(e.file);if(t){if(t.owner.id!==e.owner.id||!Rh(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ph(t,Xe.dirname(e.file))}}async function tV(e,t){let r=Date.now()+GB;for(;;){let i=await ZB(e,t);if(!await eV(i))return i;if(await Jx(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 rV(e){let t=Sh.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Sh.set(e,n),await t,()=>{r(),Sh.get(e)===n&&Sh.delete(e)}}async function xh(e,t,r){let i=Xe.resolve(e.locksDir),n=Lx.getStore();if(n?.has(i))return r();let a=await rV(i);try{let o=await tV(e,t),s=new Map(n??[]);return s.set(i,o),await Lx.run(s,async()=>{try{return await r()}finally{await Jx(o)}})}finally{a()}}async function Vo(e,t,r){let i=[...new Map(e.map(a=>[Xe.resolve(a.locksDir),a])).values()].sort((a,o)=>Xe.resolve(a.locksDir).localeCompare(Xe.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?xh(o,t,()=>n(a+1)):r()};return n(0)}async function An(e,t,r){return xh(e,`acquire ${t}`,async()=>{let i=await T(e.runtimeDir,e.locksDir);await ii.mkdir(i,{recursive:!0});let n=await T(e.runtimeDir,Xe.join(i,KB(t))),a=await Wx(r),o=await zx(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function In(e){await Ai(e.file)&&await xh({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Xe.basename(e.file)}`,async()=>{let t=await Ai(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Rh(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Xe.join(e.locksDir,Hy);await Ph(t,r)})}function qy(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function Du(e){return Fy(await Ai(e))}async function Wo(e,t,r,i={}){return xh(e,`take over ${Xe.basename(t)}`,async()=>{let n=await T(e.runtimeDir,e.locksDir),a=await T(e.runtimeDir,t);if(Xe.resolve(Xe.dirname(a))!==Xe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await Ai(a),s=await Fy(o);if(s.status==="missing")return{status:"missing"};if(r&&!YB(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&qy(o?.owner??null)>=Ou;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=Xe.join(n,Hy);return await Ph(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var qx,Hy,GB,Ou,Lx,Sh,zo=W(()=>{"use strict";Cu();$u();Z();ei();qx=16*1024,Hy=".coordinator",GB=5e3,Ou=900*1e3,Lx=new JB,Sh=new Map});var it,st,nr,ja,jn,Jo,cc=W(()=>{"use strict";it="comet.native.v3",st="comet.native.v2",nr="comet.native.v1",ja="comet.native.transition.v3",jn="comet.native.transition.v2",Jo="comet.native.transition.v1"});import iV from"node:path";function Fu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Yx(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 Tn(e){if(!Ux.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Xx(e){if(!Ux.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Qx(e,t){if(e.length===0||iV.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function dV(e,t){let r=Fu(e,`spec_changes[${t}]`);if(Yx(r,oV,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Xx(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"&&Qx(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"||!My.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"||!My.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 fV(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 By(e,t){if(Yx(e,t,ct),typeof e.name!="string")throw new Error("Native change name is required");if(Tn(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"||!sV.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&&!cV.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(dV),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"||!lV.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"&&Qx(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!fV(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 Ta(e){let t=Fu(e,ct);if(t.schema!==nr)throw new Error(`Expected ${nr}`);return{schema:nr,...By(t,nV)}}function Hu(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ly(e,t,r){if(e===null)return null;let i=typeof e=="string"?uV.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 pV(e){if(e==null)return null;if(typeof e!="string"||!My.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function hV(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 Ii(e){let t=Fu(e,ct);if(t.schema!==st)throw new Error(`Expected ${st}`);if(Hu(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${st} minimum_runtime_version must be 2`);return{schema:st,minimum_runtime_version:2,revision:Hu(t.revision,"Native v2 revision"),...By(t,Kx)}}function zt(e){let t=Fu(e,ct);if(t.schema!==it){if(t.schema===nr||t.schema===st){let o=t.schema===nr?Ta(t):Ii(t);throw new Go(o.name,o.schema)}throw new Fr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Hu(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Fr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Hu(t.revision,"Native revision"),n=By(t,aV),a=pV(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:it,minimum_runtime_version:3,revision:i,verification_protocol:hV(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ly(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ly(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ly(t.partial_allowance,"Native partial_allowance","allowances")}}function Ch(e){let t=Fu(e,ct);if(t.schema===nr){let n=Ta(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${it}`}}if(t.schema===st){let n=Ii(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${it}`}}if(t.schema!==it){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 Fr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Hu(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Fr(t.schema,r).message};let i=zt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function $n(e){let t=zt(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 qu(e){let t=Ii(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}}var Gx,nV,Kx,aV,oV,sV,cV,lV,ct,My,Ux,uV,Go,Fr,_h=W(()=>{"use strict";cc();Gx=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],nV=new Set(Gx),Kx=new Set([...Gx,"minimum_runtime_version","revision"]),aV=new Set([...Kx,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),oV=new Set(["capability","operation","source","base_hash"]),sV=new Set(["shape","build","verify","archive"]),cV=new Set(["implicit","confirmed"]),lV=new Set(["pending","pass","fail"]),ct="comet-state.yaml",My=/^[a-f0-9]{64}$/u,Ux=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uV=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Go=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"},Fr=class extends Error{constructor(r,i){super(r!==it||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"}});import{createHash as mV}from"crypto";function ji(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function vV(e,t){t.has(e)&&ji("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)||ji("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&ji("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&ji("symbol properties are not supported"),`[${e.map(i=>Vy(i,t)).join(",")}]`}finally{t.delete(e)}}function gV(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&ji("only plain objects are supported"),t.has(e)&&ji("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&ji("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))&&ji("accessor properties are not supported"),`${JSON.stringify(o)}:${Vy(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Vy(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)||ji("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?vV(e,t):gV(e,t);case"bigint":case"function":case"symbol":case"undefined":return ji(`${typeof e} values are not supported`)}return ji("unsupported value type")}function Lu(e){return Vy(e,new Set)}function j(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 mV("sha256").update(`${e}
|
|
205
205
|
${Lu(t)}`).digest("hex")}var Qe=W(()=>{"use strict"});import Zx from"node:path";function EV(e,t){return e<t?-1:e>t?1:0}function rC(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 iC(e,t){let r=t.toString(36),i=j("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function RV(e){if(!kV.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=SV.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]!==j("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function PV(e,t){let r=rC(e.text,On.maxTextBytes),i=e.context.slice(0,On.maxContextItems).map(n=>rC(n,On.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 aC(e){let t=RV({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(EV),n=i.slice(0,On.maxFailedCheckIds),a=e.criteria.slice(t,t+On.maxItems);for(let c of a){let l=[...r,PV(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?iC(e.acceptanceHash,u):null,limits:{...On}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>On.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?iC(e.acceptanceHash,o):null,limits:{...On}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>On.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function zy(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 Wy(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 nC(e){return e.includes("-->")||e.includes("--!>")}function*lc(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
206
206
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
@@ -224,11 +224,11 @@ ${Buffer.byteLength(i)}:${i}`)}function i_(e){return e.reason==="git-enumeration
|
|
|
224
224
|
${Lu(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function Lz(e){if(Dd(e)<=ds)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=VA("sha256");a.update(`${jz}
|
|
225
225
|
`),e.omissionOverflow&&Qa(a,"existing-overflow",e.omissionOverflow);let o=(f,p)=>{p||(i+=1),n+=1,Qa(a,"omission",f)},s=f=>{i+=1,n+=1,Qa(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(;Dd(u)>ds;){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 h=0;h<p;h+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let h of t.splice(-p))s(h)}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 sb(e){let t=Fn(e),r=t.entries.map((n,a)=>Dz(n,`Snapshot entry ${a}`));if(r.sort(Fz),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)=>Hz(n,`Snapshot omission ${a}`));return i.sort(qz),Lz({schema:WA,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 Hd(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:Za(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)=>Kt(r.path,i.path)||Kt(r.kind,i.kind))}function Fd(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function HA(e){return e?{hash:e.hash,size:e.size}:null}function ub(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:Kt(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:HA(c),after:HA(l)})}}function GA(e,t){return{...e,attributedTo:t.filter(r=>Fd(r,e.path))}}function fs(e){let t=Hd(e.declaredArtifacts),r=[];return ub(e.baseline,e.current,i=>{r.push(GA(i,t))}),r}function Vn(e,t){return{id:`scope:${j(Az,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Mz(e,t){let r=t.omitted.map(i=>Vn({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(Vn({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Vn({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 FA(e,t){return Mz(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function cb(e,t){return Kt(e.kind,t.kind)||Kt(e.source,t.source)||Oz(e.path,t.path)||Kt(e.id,t.id)}function Bz(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(cb)}function KA(e){return[...new Set(e.map((t,r)=>Za(t,`Git path ${r}`)))].sort(Kt)}function qA(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 Vz(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 UA(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=KA(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:qA(e.baseCommit,"Native external drift base commit"),targetBranch:Vz(e.targetBranch,"Native external drift target branch"),targetCommit:qA(e.targetCommit,"Native external drift target commit"),paths:t}}function YA(e){if(typeof e.contractHash!="string"||!lb.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Hd(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:KA(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:UA(e.externalDrift)}}}function Wz(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 ub(e,t,p=>{let h=r.some(m=>Fd(m,p.path));if(d+=1,c.push(p.path),!h&&!n?.has(p.path)&&(f+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<Tz){let m=GA(p,r),v=Dd(m);l+v<=ds?(a.push(m),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function XA(e,t){return Vn({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 zz(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:Jc(Number(t[1]),"Scope overflow change count"),unresolved:Jc(Number(t[2]),"Scope overflow unresolved count"),unattributed:Jc(Number(t[3]),"Scope overflow unattributed count")},i=us(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(XA(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function Jz(e){let t=VA("sha256");t.update(`${Iz}
|
|
226
226
|
`);let r=0;ub(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Qa(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Fd(o,n.path)&&(a+=1,Qa(t,"change-attribution",o));Qa(t,"change-end",{attributionCount:a}),a===0&&Qa(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&&Qa(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function QA(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=Wz(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let S=new Set(r.externalDrift.paths),E=new Set(o.changePaths),N=r.externalDrift.paths.filter(P=>!E.has(P)||n.some(C=>Fd(C,P)));if(N.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${N.slice(0,8).join(", ")}`);if(S.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=j($d,e),c=j($d,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[S,E]of[["baseline",e],["current",t]])for(let N of E.omitted){if(l.length>=$z)break;l.push(Vn({kind:"snapshot-omission",source:S,path:N.path,evidence:{reason:N.reason,size:N.size,type:N.type}},`${S} snapshot omitted ${N.path}: ${N.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...FA("baseline",e),...FA("current",t),...o.totalChanges===0&&a===null?[Vn({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 S=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(E=>S.has(E)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(E=>!S.has(E))}},h=S=>{let E=o.candidates.slice(0,S.detailedChangeCount),N=E.filter(Ee=>Ee.attributedTo.length===0&&!u.has(Ee.path)),P=o.totalChanges-E.length,C=o.totalUnattributed-N.length,x=d-S.detailedOmissionCount,D=C+x,se=[...N.map(Ee=>Vn({kind:"unattributed-change",source:"implementation-scope",path:Ee.path,evidence:{after:Ee.after,before:Ee.before,changeKind:Ee.kind}},`Changed path is not covered by a declared artifact: ${Ee.path}`)),...l.slice(0,S.detailedOmissionCount),...f,...D>0?[XA(S.overflowHash,{changes:P,unattributed:C,unresolved:D})]:[]],U=Bz(se),Le=S.includeGitAdvisory?p():void 0;return{schema:ab,contractHash:i,baselineProjectionRef:ob(s),baselineProjectionHash:s,currentProjectionRef:ob(c),currentProjectionHash:c,complete:U.length===0,declaredArtifacts:n,changes:E,unattributed:N,unresolvedScopes:U,noCodeReason:a,...Le?{gitAdvisory:Le}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},m=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let S=h({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w});if(Dd({...S,scopeHash:w})<=ds)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let b=o.totalChanges>m||d>v?Jz({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:v}):w,R=h({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:b}),y={...R,scopeHash:j(zA,R)};if(Dd(y)>ds)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return y}function Kc(e){let t=sb(e.baseline),r=sb(e.current),i=YA(e);return{authority:i,baseline:t,current:r,scope:QA(t,r,i)}}function dn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fn(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 us(e,t){if(typeof e!="string"||!lb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function LA(e,t,r){let i=ob(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function Gc(e,t){let r=dn(e,"Native snapshot projection");if(fn(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==WA)throw new Error("Native snapshot projection schema is invalid");let i=Fn({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=sb(i);if(j($d,r)!==j($d,n))throw new Error("Native snapshot projection is not canonical");let a=j($d,n);if(t!==void 0&&us(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function db(e,t){let r=dn(e,`Declared artifact ${t}`);if(fn(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Za(r.path,`Declared artifact ${t} path`),kind:r.kind}}function MA(e,t){if(e===null)return null;let r=dn(e,t);return fn(r,["hash","size"],[],t),{hash:us(r.hash,`${t} hash`),size:Jc(r.size,`${t} size`)}}function BA(e,t){let r=dn(e,`Implementation change ${t}`);if(fn(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(db),n=Hd(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=MA(r.before,`Implementation change ${t} before`),o=MA(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:Za(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function Kz(e,t){let r=dn(e,`Unresolved scope ${t}`);fn(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"?JA(r.path,`Unresolved scope ${t} path`):Za(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Od(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)=>Za(n,`${t} ${a}`)),i=[...new Set(r)].sort(Kt);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function ZA(e){let t=dn(e,"Native implementation external drift");if(fn(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=Od(t.paths,"Native external drift paths");return UA({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Uc(e){let t=dn(e,"Native implementation scope"),r=[...Gz].filter(N=>N!=="gitAdvisory"&&N!=="externalDrift");if(fn(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==ab)throw new Error("Native implementation scope schema is invalid");let i=us(t.contractHash,"Implementation scope contractHash"),n=us(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=LA(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=us(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=LA(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(db);if(JSON.stringify(c)!==JSON.stringify(Hd(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(BA),u=[...l].sort((N,P)=>Kt(N.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(N=>N.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(N=>`${N.kind}:${N.path}`));if(l.some(N=>N.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(N=>JSON.stringify(N.attributedTo)!==JSON.stringify(c.filter(P=>Fd(P,N.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(BA),p=t.externalDrift===void 0?void 0:ZA(t.externalDrift),h=new Set(p?.paths??[]),m=l.filter(N=>N.attributedTo.length===0&&!h.has(N.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(Kz),g=v.filter(N=>N.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:zz(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 k=t.noCodeReason,b=[...m.map(N=>Vn({kind:"unattributed-change",source:"implementation-scope",path:N.path,evidence:{after:N.after,before:N.before,changeKind:N.kind}},`Changed path is not covered by a declared artifact: ${N.path}`)),...l.length+(w?.changes??0)===0&&k===null?[Vn({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")]:[]],R=v.filter(N=>N.kind==="unattributed-change"||N.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(cb))||new Set(v.map(N=>N.id)).size!==v.length||JSON.stringify(R)!==JSON.stringify(b.sort(cb))||t.complete!==(v.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 y;if(t.gitAdvisory!==void 0){let N=dn(t.gitAdvisory,"Implementation scope Git advisory");if(fn(N,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),N.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=Od(N.changedPaths,"Git changed paths"),C=Od(N.pathsPresentInSnapshotChanges,"Git present paths"),x=Od(N.pathsAbsentFromSnapshotChanges,"Git absent paths"),D=[...C,...x].sort(Kt);if(JSON.stringify(D)!==JSON.stringify(P)||x.some(se=>l.some(U=>U.path===se)))throw new Error("Implementation scope Git advisory partition is invalid");y={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:C,pathsAbsentFromSnapshotChanges:x}}let S={schema:ab,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:k,...y?{gitAdvisory:y}:{},...p?{externalDrift:p}:{}},E=us(t.scopeHash,"Implementation scope scopeHash");if(j(zA,S)!==E)throw new Error("Implementation scope content hash mismatch");return{...S,scopeHash:E}}function Uz(e){let t=dn(e,"Native implementation scope authority");if(fn(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(db);if(JSON.stringify(r)!==JSON.stringify(Hd(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=Od(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:ZA(t.externalDrift),a=YA({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 Yc(e){let t=dn(e,"Native implementation scope bundle");fn(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=Uz(t.authority),i=Gc(t.baseline),n=Gc(t.current),a=Uc(t.scope),o=QA(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 eI(e){let t=Uc(e.scope);return Yc({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 ab,WA,$d,zA,Az,Iz,jz,lb,ds,Tz,$z,Gz,Wn=W(()=>{"use strict";Qe();Ba();ab="comet.native.implementation-scope.v2",WA="comet.native.content-snapshot-projection.v1",$d="comet.native.content-snapshot-projection.v1",zA="comet.native.implementation-scope.v2",Az="comet.native.unresolved-scope-id.v1",Iz="comet.native.scope-detail-overflow.v1",jz="comet.native.snapshot-projection-overflow.v2",lb=/^[a-f0-9]{64}$/u,ds=1024*1024,Tz=128,$z=128;Gz=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import tI from"node:path";function zn(e,t){if(!iI.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function nI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function aI(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 fb(e,t,r=2e3){let i=Rt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function qd(e,t){let r=tI.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})||tI.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 Zz(e,t,r){let i=qd(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Ki(i),a=i.toLowerCase(),o=r?qd(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 pb(e){let t=qd(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 Xc(e,t){return e<t?-1:e>t?1:0}function Bm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vm(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 oI(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 rI(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 eJ(e){let t=Bm(e,"Native acceptance trace");if(Vm(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"||!iI.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=qd(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Bm(o,`Native acceptance trace entry ${s}`);if(Vm(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=>pb(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Xc))||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:qd(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:fb(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Xc(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=zn(t.traceHash,"Native acceptance trace hash");if(j(Yz,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Wm(e){let t=Bm(e,"Native partial allowance");if(Vm(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(Xc))||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:aI(t.change),scopeHash:zn(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:fb(t.reason,"Partial allowance reason"),confirmedSummary:fb(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:nI(t.sourceRevision),confirmedAt:oI(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=zn(t.allowanceHash,"Native partial allowance hash");if(j(Xz,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ld(e){let t=Bm(e,"Native verification evidence");if(Vm(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=zn(t.implementationScopeHash,"Native verification implementation scope hash"),i=eJ(t.acceptanceTrace),n=zn(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:zn(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>pb(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Xc)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(Xc);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=>pb(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Xc)))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:aI(t.change),sourceRevision:nI(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:zn(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:rI(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:Zz(t.reportRef,"Native verification report ref"),reportHash:zn(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:rI(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:oI(t.createdAt,"Native verification timestamp")},d=zn(t.envelopeHash,"Native verification envelope hash");if(j(Qz,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var iI,Yz,Xz,Qz,Md=W(()=>{"use strict";Qe();Bn();Ll();Wn();iI=/^[a-f0-9]{64}$/u,Yz="comet.native.acceptance-trace.v2",Xz="comet.native.partial-allowance.v1",Qz="comet.native.verification-evidence.v2"});import sI from"node:path";function to(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ro(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 Jn(e,t){if(typeof e!="string"||!tJ.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Jr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function fI(e,t){let r=Jr(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function lI(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 cJ(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>aJ||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=sI.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||sI.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function lJ(e){let t=to(e,"Native check receipt checker");ro(t,["policy","version","hash","limits"],"Native check receipt checker");let r=to(t.limits,"Native check receipt limits");if(ro(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==eo||t.version!==Bd||t.hash!==Jm||r.maxFiles!==We.maxFiles||r.maxFileBytes!==We.maxFileBytes||r.maxTotalBytes!==We.maxTotalBytes||r.maxIssues!==We.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:eo,version:Bd,hash:Jm,limits:{...We}}}function uJ(e){let t=to(e,"Native check receipt contract");return ro(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Jn(t.expectedHash,"Native check expected contract hash"),beforeHash:Jn(t.beforeHash,"Native check before contract hash"),afterHash:Jn(t.afterHash,"Native check after contract hash")}}function dJ(e){let t=to(e,"Native check receipt implementation");return ro(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Jn(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Jn(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Jn(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Jn(t.afterSnapshotHash,"Native check after snapshot hash")}}function fJ(e,t){let r=to(e,`Native check batch ${t}`);ro(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:Jr(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:Jr(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:Jr(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:Jr(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:Jr(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:Jr(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>We.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>We.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function pJ(e){let t=to(e,"Native check receipt counts");ro(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:Jr(t.filesSelected,"Native check filesSelected"),filesScanned:Jr(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:Jr(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:Jr(t.bytesScanned,"Native check bytesScanned"),issueCount:Jr(t.issueCount,"Native check issueCount"),recordedIssueCount:Jr(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(fJ):(()=>{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>We.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>We.maxFiles||r.bytesScanned>We.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function hJ(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||cI.indexOf(e.kind)-cI.indexOf(t.kind)}function mJ(e){if(!Array.isArray(e)||e.length>We.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=to(i,`Native check issue ${n}`);if(ro(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!oJ.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:cJ(a.path,`Native check issue ${n} path`),line:fI(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(hJ);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function vJ(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!sJ.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=dI.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 pI(e){return j(nJ,e)}function Gn(e){let t=to(e,"Native check receipt");if(ro(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==zm)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!rJ.test(t.change))throw new Error("Native check receipt change name is invalid");let r=fI(t.sourceRevision,"Native check source revision"),i=lJ(t.checker),n=uJ(t.contract),a=dJ(t.implementation),o=pI({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Jn(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=lI(t.startedAt,"Native check receipt startedAt"),c=lI(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=pJ(t.counts),u=mJ(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=vJ(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>We.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>We.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let p={schema:zm,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},h=Jn(t.receiptHash,"Native check receipt content hash");if(j(uI,p)!==h)throw new Error("Native check receipt content hash mismatch");return{...p,receiptHash:h}}function hI(e){let t={policy:eo,version:Bd,hash:Jm,limits:{...We}},r={schema:zm,...e,checker:t,inputHash:pI({change:e.change,sourceRevision:e.sourceRevision,checkerHash:t.hash,contractHash:e.contract.expectedHash,scopeHash:e.implementation.scopeHash,snapshotHash:e.implementation.expectedSnapshotHash})};return Gn({...r,receiptHash:j(uI,r)})}var zm,uI,eo,Bd,We,tJ,rJ,iJ,nJ,aJ,Jm,oJ,cI,dI,sJ,Qc=W(()=>{"use strict";Qe();zm="comet.native.check-receipt.v1",uI="comet.native.check-receipt.v1",eo="scoped-text-safety",Bd=1,We=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),tJ=/^[a-f0-9]{64}$/u,rJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,iJ="comet.native.checker-policy.v1",nJ="comet.native.check-input.v1",aJ=2048,Jm=j(iJ,{policy:eo,version:Bd,limits:We,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),oJ=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),cI=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],dI=["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"],sJ=new Set(dI)});function Zc(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 io(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 Kn(e,t){if(typeof e!="string"||!wJ.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Di(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Rt(e).trim();if(!r||r.length>kJ||r!==e.trim())throw new Error(`${t} is invalid`);return r}function hb(e,t){let r=Di(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 Vd(e,t,r=Di,i=!1,n=SJ){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 RJ(e,t){if(typeof e!="string"||!yJ.test(e))throw new Error(`${t} is invalid`);return e}function PJ(e){let t=Zc(e,"Native verification receipt bindings");if(io(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!NJ.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:Kn(t.contractHash,"Native verification receipt contract hash"),scopeHash:Kn(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Kn(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Kn(t.artifactHash,"Native verification receipt artifact hash")}}function xJ(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=bJ.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function CJ(e,t,r,i){let n=Zc(t,`Native ${e} evidence`);if(e==="automated-check"){if(io(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=hb(n.startedAt,"Native automated-check start time"),o=hb(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=Zc(n.worktree,"Native automated-check worktree");if(io(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=Zc(n.afterFence,"Native automated-check after fence");if(io(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:Di(n.executable,"Native automated-check executable"),args:Vd(n.args,"Native automated-check arguments",Di,!0),cwd:Di(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:Di(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Kn(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Kn(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Kn(n.outputHash,"Native automated-check output hash"),outputSummary:Di(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){io(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=xJ(n.checkReceiptRef);if(Kn(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:Vd(n.subjects,"Native static inspection subjects",Di,i==="required-check"),rule:Di(n.rule,"Native static inspection rule"),resultSummary:Di(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return io(n,["steps","observations"],"Native manual-evidence evidence"),{steps:Vd(n.steps,"Native manual evidence steps"),observations:Vd(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function vI(e){let t=Zc(e,"Native verification receipt");if(io(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=Di(t.actor,"Native verification receipt actor"),o=Vd(t.acceptanceIds,"Native receipt acceptance IDs",RJ,i==="required-check",EJ).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:Gm,kind:r,role:i,status:n,bindings:PJ(t.bindings),acceptanceIds:o,actor:a,issuedAt:hb(t.issuedAt,"Native verification receipt issue time"),evidence:CJ(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==eo||s.actor!==`native-runtime:${eo}`))throw new Error("Native required check policy identity is invalid");return s}function gI(e){let t=vI({schema:Gm,...e});return{...t,receiptHash:j(mI,t)}}function Wd(e){let t=Zc(e,"Native verification receipt");if(io(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Gm)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=vI(i),a=Kn(t.receiptHash,"Native verification receipt hash");if(j(mI,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Km(e){return j(gJ,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var Gm,mI,gJ,wJ,yJ,NJ,bJ,kJ,SJ,EJ,el=W(()=>{"use strict";Qe();Qc();Bn();Gm="comet.native.verification-receipt.v3",mI=Gm,gJ="comet.native.declared-artifacts.v1",wJ=/^[a-f0-9]{64}$/u,yJ=/^acceptance-[a-f0-9]{64}$/u,NJ=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bJ=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,kJ=4096,SJ=256,EJ=1024});var RI={};Jf(RI,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>pi,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>_J,listNativeVerificationReceiptRefs:()=>kb,nativeEvidenceRef:()=>Fi,nativeReportEvidenceRef:()=>vb,readArchivedNativeVerificationAcceptanceCounts:()=>qJ,readNativeImplementationScope:()=>rl,readNativeImplementationScopeBundle:()=>Un,readNativePartialAllowance:()=>Gd,readNativeVerificationEvidence:()=>vs,readNativeVerificationReceipt:()=>ms,readNativeVerificationReportSnapshot:()=>Jd,removeNativeVerificationReportSnapshot:()=>gb,writeNativeImplementationScope:()=>HJ,writeNativePartialAllowance:()=>FJ,writeNativeVerificationEvidence:()=>EI,writeNativeVerificationReceipt:()=>bb,writeNativeVerificationReportSnapshot:()=>tl});import{createHash as bI}from"node:crypto";import{promises as hr}from"node:fs";import Hi from"node:path";function mb(e,t){let r=Hi.relative(e,t);return r===""||!Hi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Hi.sep}`)}function AJ(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function zd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Tr(r,i)?ne(r,i):ne(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function wI(e){let t=await hr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await hr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function IJ(e,t){let r=Hi.resolve(e),i=Hi.resolve(t);if(!mb(r,i))throw new Error("Native evidence path is outside its change");let n=[await wI(r)],a=r;for(let o of Hi.relative(r,i).split(Hi.sep).filter(Boolean)){a=Hi.join(a,o);let s=await wI(a);if(!mb(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function yI(e){for(let t of e){let r=await hr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!AJ(t,r)||await hr.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function jJ(e,t,r={}){let i=await IJ(t,Hi.dirname(e));await r.afterParentChainCaptured?.();let n=await hr.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await hr.realpath(e);if(!mb(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await hr.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),hr.lstat(e),hr.realpath(e)]);if(await yI(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!zd(s,n)||!zd(s,c))throw new Error("Native evidence document changed while opening");if(s.size>pi)throw new Error(`Native evidence document exceeds ${pi} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=pi+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>pi)throw new Error(`Native evidence document exceeds ${pi} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,h,m]=await Promise.all([o.stat(),hr.lstat(e),hr.realpath(e)]);if(await yI(i),!h.isFile()||h.isSymbolicLink()||m!==a||!zd(s,p)||!zd(s,h))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(!kI.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function vb(e){return Fi("reports",e)}async function tl(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>pi||bI("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return hs({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 gb(e){let t=wb(e.paths,e.name,"reports",e.hash),r=B(e.paths,t);await T(r,t);let i=await hr.lstat(t);if(await Jd(e.paths,e.name,e.hash),await T(r,t),!zd(i,await hr.lstat(t)))throw new Error("Native report evidence changed before rollback");await hr.unlink(t)}async function Jd(e,t,r,i,n){if(!kI.test(r))throw new Error("Native report evidence hash is invalid");let a=await pn({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"||bI("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 ps(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 wb(e,t,r,i,n){let a=Fi(r,i);return n?Hi.join(n,...a.split("/")):Ia(Q(e,t),a)}async function pn(e){let t=wb(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??B(e.paths,t);return await T(r,t),jJ(t,r,e.hooks)}async function hs(e){Um(e.value);let t=wb(e.paths,e.name,e.kind,e.hash),r=B(e.paths,t);await T(r,t);try{let n=await pn(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 ve(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await pn(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 Um(e){if(TJ(e)>pi)throw new Error(`Native evidence document exceeds ${pi} bytes`)}function TJ(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
227
|
-
`,"utf8")}function NI(e,t){return Gc(e,t)}function $J(e,t){let r=Uc(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function SI(e,t,r){let i=Wm(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function yb(e,t,r){let i=Ld(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function OJ(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function DJ(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 Nb(e,t,r,i=!1,n){let a=await rl(e,t,r.implementationScopeRef,void 0,n);if(i&&await Jd(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 Gd(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 HJ(e){let t=Yc(e.bundle),{baseline:r,current:i,scope:n}=t;return Um(r),Um(i),Um(n),await hs({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await hs({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),hs({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function Un(e,t,r,i,n){let a=ps(r,"scopes"),o=$J(await pn({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=ps(o.baselineProjectionRef,"snapshots"),c=ps(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([pn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>NI(d,s)),pn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>NI(d,c))]);return eI({baseline:l,current:u,scope:o})}async function rl(e,t,r,i,n){return(await Un(e,t,r,i,n)).scope}async function FJ(e){let t=SI(e.allowance,e.name,e.allowance.allowanceHash),r=await rl(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 hs({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Gd(e,t,r,i,n){let a=ps(r,"allowances");return SI(await pn({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function bb(e){let t=Wd(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return hs({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function ms(e,t,r,i,n){let a=ps(r,"receipts"),o=Wd(await pn({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 kb(e,t){let r=Hi.join(Q(e,t),"evidence","receipts");await T(B(e,r),r);let i;try{i=await hr.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 EI(e){let t=yb(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 Nb(e.paths,e.name,t,!0),hs({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function vs(e,t,r,i,n){let a=ps(r,"verifications"),o=yb(await pn({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Nb(e,t,o,!1,n),o}async function qJ(e,t,r,i){let n=ps(r,"verifications"),a=await pn({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=DJ(a,t,n);if(o)return o;let s=yb(a,t,n);return await Nb(e,t,s,!1,i),OJ(s.acceptanceTrace)}var kI,pi,_J,hi=W(()=>{"use strict";Oe();Z();ei();Wn();Md();el();kI=/^[a-f0-9]{64}$/u,pi=ds,_J=3*pi});var xI={};Jf(xI,{executeNativeSupervisorChecks:()=>Rb,readNativeSupervisorCheckEvidence:()=>il});import{createHash as LJ,randomUUID as MJ}from"node:crypto";import{promises as PI}from"node:fs";import Eb from"node:path";function Ud(e){return LJ("sha256").update(e).digest("hex")}function Sb(e,t){if(_(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||_(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!zr(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function Kd(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 BJ(e,t){return Promise.all(t.map(async r=>{let i=Hm(r),n=await T(e,Eb.resolve(e,...i.logRef.split(/[\\/]/u))),a=await PI.readFile(n,"utf8"),o=Rt(a);return{...i,logContent:o.slice(0,128*1024),logDigest:Ud(o)}}))}function VJ(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function WJ(e){try{let t=je(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await T(t,Eb.resolve(t,...i.logRef.split(/[\\/]/u))),a=Rt(await PI.readFile(n,"utf8"));return Ud(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function zJ(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function JJ(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Rb(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=zJ(e.retryCheckIds),r=await A(e.paths,"reserve Supervisor checks",async()=>{let l=await J(e.paths,e.parent),u=Kd(l,e.child,e.runId);Sb(e.parent,u),Wr(u.projectRoot,e.plans);let d=qm(),f=await Fm({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),p=j("comet.native.supervisor-check-plan.v2",{machineId:d,inputFingerprint:f}),h=u.checkExecution;if(h?.status==="running"){let w=await sc(h.ownerPid,h.ownerIdentity),k=Date.parse(h.expiresAt??"")||Date.parse(h.startedAt)+3e4;if(w){if(!(Date.now()<k))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(h.key!==p)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let b=h.activeProcess;if(b===void 0||b?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Eb.join(je(e.paths,e.parent),"logs","checks")} for operation ${h.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(b&&await sc(b.pid,b.identity)){if(!(Date.now()<k))throw new Error(`Native Supervisor check ${b.checkId} is still running as PID ${b.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(h.checkStates?.length&&h.checkStates.every(({status:y})=>y==="passed"||y==="failed")&&h.receiptRef){h.status="completed";try{return await il({...e,task:u,receiptRef:h.receiptRef}),l.stateVersion+=1,await oe(e.paths,l),{task:structuredClone(u),execute:!1,key:h.key}}catch{h.status="interrupted"}}h.status="interrupted";for(let y of h.checkStates??[])(y.status==="planned"||y.status==="running")&&(y.status="interrupted")}let m=h?.key===p&&h.machineId===d&&h.inputFingerprint===f;if(t){if(!m||h?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");JJ(h.checkStates,e.plans,t)}else if(h?.status==="interrupted"&&m)return{task:structuredClone(u),execute:!1,key:p};if(h?.status==="completed"&&m&&h.receiptRef)try{return await il({...e,task:u,receiptRef:h.receiptRef}),{task:structuredClone(u),execute:!1,key:p}}catch{}let v=t&&h?.checkStates?h.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(Wc),g=e.plans.map(w=>v.find(k=>k.id===w.id)??Wc(w));return u.checkExecution={operationId:MJ(),key:p,status:"running",ownerPid:process.pid,ownerIdentity:await Hr(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,k)=>w+k.timeoutMs,0)+3e4).toISOString(),machineId:d,inputFingerprint:f,checkStates:g},u.checksReason="running",l.stateVersion+=1,await oe(e.paths,l),{task:structuredClone(u),execute:!0,key:p,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await il({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=je(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await A(e.paths,"register Supervisor check process",async()=>{let u=await J(e.paths,e.parent),d=Kd(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let f=d.checkExecution.checkStates?.find(({id:p})=>p===l.checkId);if(!f||f.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);f.status="running",f.executionCount+=1,f.startedAt=new Date().toISOString(),f.completedAt=null,f.logRef=null}d.checkExecution.activeProcess=l,u.stateVersion+=1,await oe(e.paths,u)})},c=async l=>A(e.paths,"record Supervisor check result",async()=>{let u=await J(e.paths,e.parent),d=Kd(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let f=d.checkExecution.checkStates?.find(({id:p})=>p===l.id);if(!f)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(f,Dm(f,l)),d.checkExecution.activeProcess=null,u.stateVersion+=1,await oe(e.paths,u)});try{for(let v of o){await s({status:"starting",checkId:v.id});let g=await cs({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:v,onSpawn:async({pid:w})=>{await s({status:"running",checkId:v.id,pid:w,identity:await Hr(w)??void 0})}});if(await c(g),g.status==="interrupted")throw new Error(`Native Supervisor check ${g.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await J(e.paths,e.parent),u=Kd(l,e.child,e.runId);Sb(e.parent,u);let d=u.checkExecution?.checkStates;if(!d||d.some(({status:v})=>!["passed","failed"].includes(v)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let f=await BJ(a,d),p={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:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:f,materials:e.materials.map(({name:v,content:g})=>{let w=Rt(g);return{name:v,content:w,hash:Ud(w)}})},h=JSON.stringify(p),m=await tl({paths:e.paths,name:e.parent,hash:Ud(h),text:h});return await A(e.paths,"complete Supervisor checks",async()=>{let v=await J(e.paths,e.parent),g=Kd(v,e.child,e.runId);if(g.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Sb(e.parent,g),g.checkExecution.status="completed",g.checkExecution.receiptRef=m,g.checkExecution.activeProcess=null,g.checksReason="completed",v.stateVersion+=1,await oe(e.paths,v)}),{status:"completed",operationId:n,receiptRef:m}}catch(l){throw await A(e.paths,"interrupt Supervisor checks",async()=>{let u=await J(e.paths,e.parent),d=u?.children.find(({name:f})=>f===e.child)?.task;if(d?.runId===e.runId&&d.checkExecution?.operationId===n){d.checkExecution.status="interrupted",d.checkExecution.activeProcess=null;for(let f of d.checkExecution.checkStates??[])(f.status==="planned"||f.status==="running")&&(f.status="interrupted");d.checksReason="not-run",u.stateVersion+=1,await oe(e.paths,u)}}),l}}async function il(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 Jd(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>VJ(s,n[c])),o=Array.isArray(r.checks)&&await WJ({paths:e.paths,parent:e.parent,checks:r.checks});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||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>Ud(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Pb=W(()=>{"use strict";ls();fr();$u();Qe();Vc();ib();hi();Fe();Z();Bn();ln()});import{pathToFileURL as R8}from"url";import Pl from"node:path";import{randomUUID as AY}from"node:crypto";import{randomUUID as eK}from"node:crypto";import{promises as ze}from"node:fs";import Nt from"node:path";import{execFileSync as OD}from"child_process";import DD from"fs";import pa from"path";function Sn(e,t){return OD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Gi(e,t){return aE(e)===aE(t)}function aE(e){let t=pa.resolve(e);try{let r=DD.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ie(e){try{let t=pa.resolve(Sn(e,["rev-parse","--show-toplevel"])),i=Sn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?pa.resolve(i.slice(9)):t,a=null;try{a=Sn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Gi(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Hs(e){try{Sn(e,["rev-parse","--is-inside-work-tree"]);let t=Sn(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:pa.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 Vt(e){return Hs(e).map(t=>t.root)}function gg(e,t){let r=t.find(a=>Gi(pa.resolve(a.root),pa.resolve(e)));if(!r)return null;let i=pa.resolve(t[0].root),n=pa.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Gi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function oE(e){try{return Sn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function ha(e,t){try{return Sn(e,["check-ref-format","--branch",t]),Sn(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function er(e,t){try{let r=Sn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}Oe();Ht();Xs();var gm=Ji(Ri(),1);import{promises as sd}from"fs";import Br from"path";Ht();Oe();To();ot();Fe();Z();cr();function OC(e){return Number.isSafeInteger(e)&&e>=1}async function DC(e){if(!OC(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(!OC(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}Ba();import{createHash as v2}from"crypto";import g2 from"path";var Lr=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"});Fe();Z();import{createHash as u2}from"node:crypto";import{constants as um,promises as ur}from"node:fs";import Mr from"node:path";import{TextDecoder as d2}from"node:util";import o2 from"path";tc();Ca();var GW=Ji(Ri(),1);tc();Ca();_n();_n();Fo();Py();tc();_n();import{promises as KW}from"node:fs";import UW from"node:path";var Rc=".gitignore",bN=4*1024*1024,SN="# >>> Comet managed project state >>>",c_="# <<< Comet managed project state <<<";function YW(e){return e.includes(`\r
|
|
227
|
+
`,"utf8")}function NI(e,t){return Gc(e,t)}function $J(e,t){let r=Uc(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function SI(e,t,r){let i=Wm(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function yb(e,t,r){let i=Ld(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function OJ(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function DJ(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 Nb(e,t,r,i=!1,n){let a=await rl(e,t,r.implementationScopeRef,void 0,n);if(i&&await Jd(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 Gd(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 HJ(e){let t=Yc(e.bundle),{baseline:r,current:i,scope:n}=t;return Um(r),Um(i),Um(n),await hs({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await hs({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),hs({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function Un(e,t,r,i,n){let a=ps(r,"scopes"),o=$J(await pn({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=ps(o.baselineProjectionRef,"snapshots"),c=ps(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([pn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>NI(d,s)),pn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>NI(d,c))]);return eI({baseline:l,current:u,scope:o})}async function rl(e,t,r,i,n){return(await Un(e,t,r,i,n)).scope}async function FJ(e){let t=SI(e.allowance,e.name,e.allowance.allowanceHash),r=await rl(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 hs({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Gd(e,t,r,i,n){let a=ps(r,"allowances");return SI(await pn({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function bb(e){let t=Wd(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return hs({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function ms(e,t,r,i,n){let a=ps(r,"receipts"),o=Wd(await pn({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 kb(e,t){let r=Hi.join(Q(e,t),"evidence","receipts");await T(B(e,r),r);let i;try{i=await hr.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 EI(e){let t=yb(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 Nb(e.paths,e.name,t,!0),hs({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function vs(e,t,r,i,n){let a=ps(r,"verifications"),o=yb(await pn({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Nb(e,t,o,!1,n),o}async function qJ(e,t,r,i){let n=ps(r,"verifications"),a=await pn({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=DJ(a,t,n);if(o)return o;let s=yb(a,t,n);return await Nb(e,t,s,!1,i),OJ(s.acceptanceTrace)}var kI,pi,_J,hi=W(()=>{"use strict";Oe();Z();ei();Wn();Md();el();kI=/^[a-f0-9]{64}$/u,pi=ds,_J=3*pi});var xI={};Jf(xI,{executeNativeSupervisorChecks:()=>Rb,readNativeSupervisorCheckEvidence:()=>il});import{createHash as LJ,randomUUID as MJ}from"node:crypto";import{promises as PI}from"node:fs";import Eb from"node:path";function Ud(e){return LJ("sha256").update(e).digest("hex")}function Sb(e,t){if(_(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||_(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!zr(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function Kd(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 BJ(e,t){return Promise.all(t.map(async r=>{let i=Hm(r),n=await T(e,Eb.resolve(e,...i.logRef.split(/[\\/]/u))),a=await PI.readFile(n,"utf8"),o=Rt(a);return{...i,logContent:o.slice(0,128*1024),logDigest:Ud(o)}}))}function VJ(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function WJ(e){try{let t=je(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await T(t,Eb.resolve(t,...i.logRef.split(/[\\/]/u))),a=Rt(await PI.readFile(n,"utf8"));return Ud(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function zJ(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function JJ(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Rb(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=zJ(e.retryCheckIds),r=await A(e.paths,"reserve Supervisor checks",async()=>{let l=await J(e.paths,e.parent),u=Kd(l,e.child,e.runId);Sb(e.parent,u),Wr(u.projectRoot,e.plans);let d=qm(),f=await Fm({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),p=j("comet.native.supervisor-check-plan.v2",{machineId:d,inputFingerprint:f}),h=u.checkExecution;if(h?.status==="running"){let w=await sc(h.ownerPid,h.ownerIdentity),k=Date.parse(h.expiresAt??"")||Date.parse(h.startedAt)+3e4;if(w){if(!(Date.now()<k))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(h.key!==p)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let b=h.activeProcess;if(b===void 0||b?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Eb.join(je(e.paths,e.parent),"logs","checks")} for operation ${h.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(b&&await sc(b.pid,b.identity)){if(!(Date.now()<k))throw new Error(`Native Supervisor check ${b.checkId} is still running as PID ${b.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(h.checkStates?.length&&h.checkStates.every(({status:y})=>y==="passed"||y==="failed")&&h.receiptRef){h.status="completed";try{return await il({...e,task:u,receiptRef:h.receiptRef}),l.stateVersion+=1,await oe(e.paths,l),{task:structuredClone(u),execute:!1,key:h.key}}catch{h.status="interrupted"}}h.status="interrupted";for(let y of h.checkStates??[])(y.status==="planned"||y.status==="running")&&(y.status="interrupted")}let m=h?.key===p&&h.machineId===d&&h.inputFingerprint===f;if(t){if(!m||h?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");JJ(h.checkStates,e.plans,t)}else if(h?.status==="interrupted"&&m)return{task:structuredClone(u),execute:!1,key:p};if(h?.status==="completed"&&m&&h.receiptRef)try{return await il({...e,task:u,receiptRef:h.receiptRef}),{task:structuredClone(u),execute:!1,key:p}}catch{}let v=t&&h?.checkStates?h.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(Wc),g=e.plans.map(w=>v.find(k=>k.id===w.id)??Wc(w));return u.checkExecution={operationId:MJ(),key:p,status:"running",ownerPid:process.pid,ownerIdentity:await Hr(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,k)=>w+k.timeoutMs,0)+3e4).toISOString(),machineId:d,inputFingerprint:f,checkStates:g},u.checksReason="running",l.stateVersion+=1,await oe(e.paths,l),{task:structuredClone(u),execute:!0,key:p,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await il({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=je(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await A(e.paths,"register Supervisor check process",async()=>{let u=await J(e.paths,e.parent),d=Kd(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let f=d.checkExecution.checkStates?.find(({id:p})=>p===l.checkId);if(!f||f.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);f.status="running",f.executionCount+=1,f.startedAt=new Date().toISOString(),f.completedAt=null,f.logRef=null}d.checkExecution.activeProcess=l,u.stateVersion+=1,await oe(e.paths,u)})},c=async l=>A(e.paths,"record Supervisor check result",async()=>{let u=await J(e.paths,e.parent),d=Kd(u,e.child,e.runId);if(d.checkExecution?.operationId!==n||d.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let f=d.checkExecution.checkStates?.find(({id:p})=>p===l.id);if(!f)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(f,Dm(f,l)),d.checkExecution.activeProcess=null,u.stateVersion+=1,await oe(e.paths,u)});try{for(let v of o){await s({status:"starting",checkId:v.id});let g=await cs({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:v,onSpawn:async({pid:w})=>{await s({status:"running",checkId:v.id,pid:w,identity:await Hr(w)??void 0})}});if(await c(g),g.status==="interrupted")throw new Error(`Native Supervisor check ${g.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await J(e.paths,e.parent),u=Kd(l,e.child,e.runId);Sb(e.parent,u);let d=u.checkExecution?.checkStates;if(!d||d.some(({status:v})=>!["passed","failed"].includes(v)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let f=await BJ(a,d),p={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:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:f,materials:e.materials.map(({name:v,content:g})=>{let w=Rt(g);return{name:v,content:w,hash:Ud(w)}})},h=JSON.stringify(p),m=await tl({paths:e.paths,name:e.parent,hash:Ud(h),text:h});return await A(e.paths,"complete Supervisor checks",async()=>{let v=await J(e.paths,e.parent),g=Kd(v,e.child,e.runId);if(g.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Sb(e.parent,g),g.checkExecution.status="completed",g.checkExecution.receiptRef=m,g.checkExecution.activeProcess=null,g.checksReason="completed",v.stateVersion+=1,await oe(e.paths,v)}),{status:"completed",operationId:n,receiptRef:m}}catch(l){throw await A(e.paths,"interrupt Supervisor checks",async()=>{let u=await J(e.paths,e.parent),d=u?.children.find(({name:f})=>f===e.child)?.task;if(d?.runId===e.runId&&d.checkExecution?.operationId===n){d.checkExecution.status="interrupted",d.checkExecution.activeProcess=null;for(let f of d.checkExecution.checkStates??[])(f.status==="planned"||f.status==="running")&&(f.status="interrupted");d.checksReason="not-run",u.stateVersion+=1,await oe(e.paths,u)}}),l}}async function il(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 Jd(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>VJ(s,n[c])),o=Array.isArray(r.checks)&&await WJ({paths:e.paths,parent:e.parent,checks:r.checks});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||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>Ud(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Pb=W(()=>{"use strict";ls();fr();$u();Qe();Vc();ib();hi();Fe();Z();Bn();ln()});import{pathToFileURL as P8}from"url";import Pl from"node:path";import{randomUUID as IY}from"node:crypto";import{randomUUID as tK}from"node:crypto";import{promises as ze}from"node:fs";import Nt from"node:path";import{execFileSync as OD}from"child_process";import DD from"fs";import pa from"path";function Sn(e,t){return OD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Gi(e,t){return aE(e)===aE(t)}function aE(e){let t=pa.resolve(e);try{let r=DD.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ie(e){try{let t=pa.resolve(Sn(e,["rev-parse","--show-toplevel"])),i=Sn(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?pa.resolve(i.slice(9)):t,a=null;try{a=Sn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Gi(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Hs(e){try{Sn(e,["rev-parse","--is-inside-work-tree"]);let t=Sn(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:pa.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 Vt(e){return Hs(e).map(t=>t.root)}function gg(e,t){let r=t.find(a=>Gi(pa.resolve(a.root),pa.resolve(e)));if(!r)return null;let i=pa.resolve(t[0].root),n=pa.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Gi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function oE(e){try{return Sn(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function ha(e,t){try{return Sn(e,["check-ref-format","--branch",t]),Sn(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function er(e,t){try{let r=Sn(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}Oe();Ht();Xs();var gm=Ji(Ri(),1);import{promises as sd}from"fs";import Br from"path";Ht();Oe();To();ot();Fe();Z();cr();function OC(e){return Number.isSafeInteger(e)&&e>=1}async function DC(e){if(!OC(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(!OC(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}Ba();import{createHash as v2}from"crypto";import g2 from"path";var Lr=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"});Fe();Z();import{createHash as u2}from"node:crypto";import{constants as um,promises as ur}from"node:fs";import Mr from"node:path";import{TextDecoder as d2}from"node:util";import o2 from"path";tc();Ca();var GW=Ji(Ri(),1);tc();Ca();_n();_n();Fo();Py();tc();_n();import{promises as KW}from"node:fs";import UW from"node:path";var Rc=".gitignore",bN=4*1024*1024,SN="# >>> Comet managed project state >>>",c_="# <<< Comet managed project state <<<";function YW(e){return e.includes(`\r
|
|
228
228
|
`)?`\r
|
|
229
229
|
`:`
|
|
230
230
|
`}function XW(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function QW(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function l_(e){let t=[],r=!1;for(let i of XW(e)){let n=QW(i);if(n===SN){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(n===c_){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 s_(e){let t=l_(e).split(/\r?\n/u).map(r=>r.trim());return t.includes(".comet/runtime/")&&t.includes(".comet/current-change.json")}function kN(e){let t=YW(e),r=l_(e);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=t),r+[SN,"!/.comet/","/.comet/*","!/.comet/config.yaml",c_,""].join(t)}async function Qu(e){let t=UW.resolve(e),r=await Cn(t,Rc,{label:"project .gitignore",expected:"file"}),i="",n=new Uint8Array;if(r.exists&&(n=(await Wt(t,Rc,bN,{label:"project .gitignore"})).bytes,i=Buffer.from(n).toString("utf8")),r.exists&&!i.includes(SN)&&s_(i))return;let a=kN(i);if(a!==i){try{await qo(r.target,a,{containedRoot:t,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await Wt(t,Rc,bN,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await Cn(t,Rc,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}})}catch(o){let s=o instanceof Error&&o.message==="Project .gitignore was created before commit; rerun initialization";if(r.exists||o.code!=="EEXIST"&&!s)throw o;let c=await Wt(t,Rc,bN,{label:"project .gitignore"}),l=Buffer.from(c.bytes).toString("utf8");if(kN(l)!==l&&!s_(l))throw o}await Cn(t,Rc,{label:"project .gitignore",expected:"file"}),await KW.access(r.target)}}import lr from"path";var ZW=null;function e2(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function am(e,t){return(...r)=>{let i=ZW;if(i===null)return t(...r);let n=e2(`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}}Fo();var t2=am("hookWritePolicy",async e=>(await Ho(e))?.hook??{allow_paths:[]});function u_(e,t){let r=lr.relative(e,t);return r===""||!lr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${lr.sep}`)}function r2(e,t){let r=lr.isAbsolute(t)?lr.resolve(t):lr.resolve(e,t),i=lr.relative(lr.resolve(e),r);return i===""||lr.isAbsolute(i)||i===".."||i.startsWith(`..${lr.sep}`)?null:i.replaceAll("\\","/")}function d_(e){return process.platform==="win32"?e.toLowerCase():e}async function om(e,t,r=[]){let i=lr.isAbsolute(t)?lr.resolve(t):lr.resolve(e,t),n=lr.resolve(e);if(!u_(n,i)||r.some(c=>u_(lr.resolve(c),i)))return null;let a=r2(e,t);if(!a)return null;let s=(await t2(e)).allow_paths.find(c=>{let l=d_(a),u=d_(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}Cu();import{randomUUID as i2}from"node:crypto";import{promises as Zu}from"node:fs";import p_ from"node:path";var sm="comet.selection.v2",h_=16*1024;function Pc(e){return p_.join(e,".comet","current-change.json")}function n2(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function f_(e){return e===null||typeof e=="string"}function m_(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(!n2(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&&!f_(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:sm,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==sm)throw new Error(`current change selection schema must be ${sm}`);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(!f_(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 cm(e){let t;try{let i=Pc(e),{bytes:n}=await Do(i,h_,{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",...m_(t)}}async function EN(e,t){let r=m_(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=Pc(e),n=`${i}.${i2()}.tmp`;await Zu.mkdir(p_.dirname(i),{recursive:!0});try{await Zu.writeFile(n,`${JSON.stringify(r.selection,null,2)}
|
|
231
|
-
`,"utf8"),await Zu.rename(n,i)}catch(a){throw await Zu.rm(n,{force:!0}),a}}async function RN(e){await Zu.rm(Pc(e),{force:!0})}async function PN(e,t,r){let i=await cm(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await RN(e),!0)}Ey();ql();var v_=(e,t)=>{let r=e[t];return r==null?null:String(r)};function td(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 ed(e,t){let r=td(e,t);if(o2.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 s2(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 g_(e){if(!e.run_id)return null;let t=td(e,"run_id"),r=td(e,"skill"),i=td(e,"skill_version"),n=td(e,"skill_hash"),a=ed(e,"pending_ref"),o=ed(e,"trajectory_ref"),s=ed(e,"context_ref"),c=ed(e,"artifacts_ref"),l=ed(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:v_(e,"current_step"),iteration:u,pending:v_(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:s2(e)}}var
|
|
231
|
+
`,"utf8"),await Zu.rename(n,i)}catch(a){throw await Zu.rm(n,{force:!0}),a}}async function RN(e){await Zu.rm(Pc(e),{force:!0})}async function PN(e,t,r){let i=await cm(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await RN(e),!0)}Ey();ql();var v_=(e,t)=>{let r=e[t];return r==null?null:String(r)};function td(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 ed(e,t){let r=td(e,t);if(o2.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 s2(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 g_(e){if(!e.run_id)return null;let t=td(e,"run_id"),r=td(e,"skill"),i=td(e,"skill_version"),n=td(e,"skill_hash"),a=ed(e,"pending_ref"),o=ed(e,"trajectory_ref"),s=ed(e,"context_ref"),c=ed(e,"artifacts_ref"),l=ed(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:v_(e,"current_step"),iteration:u,pending:v_(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:s2(e)}}var pee=Number.MAX_SAFE_INTEGER;var c2=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function l2(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=g_(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function lm(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=>!c2.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 l2(t)}Oe();ei();var Jt={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};function id(e,t){let r=Mr.relative(e,t);return r===""||!Mr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Mr.sep}`)}function y_(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function rd(e,t){return ne({...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 f2(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Va(e,t,r){let i=Lr[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=Mr.resolve(e),a=Mr.resolve(n,...i.slice(8).split("/"));if(!id(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function w_(e){let t=await ur.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await ur.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function xN(e,t){let r=Mr.resolve(e),i=Mr.resolve(t);if(!id(r,i))throw new Error("Native Run path is outside its change");let n=[await w_(r)],a=r;for(let o of Mr.relative(r,i).split(Mr.sep).filter(Boolean)){a=Mr.join(a,o);let s;try{s=await w_(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!id(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function dm(e){for(let t of e){let r=await ur.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!f2(t,r)||await ur.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function p2(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 ts(e,t,r,i,n){let a=await xN(e,Mr.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await ur.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=y_(o),c=await ur.realpath(t);if(!id(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?um.O_RDONLY:um.O_RDONLY|um.O_NOFOLLOW|um.O_NONBLOCK,u;try{u=await ur.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,p]=await Promise.all([u.stat(),ur.lstat(t),ur.realpath(t)]);if(await dm(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||p!==c||!rd(s,d)||!rd(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let h=await p2(u,r,i);await n?.beforeFinalCheck?.();let[m,v,g]=await Promise.all([u.stat(),ur.lstat(t),ur.realpath(t)]);if(await dm(a),!v.isFile()||v.isSymbolicLink()||g!==c||!rd(s,m)||!rd(s,v))throw new Error(`${i} changed while reading`);let w;try{w=new d2("utf-8",{fatal:!0}).decode(h)}catch(k){throw new Error(`${i} is not valid UTF-8`,{cause:k})}return{text:w,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function h2(e,t,r){let i=await xN(e,Mr.dirname(t));if(!i)return{exists:!1};let n;try{n=await ur.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 ur.realpath(t);if(!id(i[0].realPath,a))throw new Error(`${r} resolves outside its change`);return await dm(i),{exists:!0,identity:y_(n),realPath:a}}async function m2(e,t,r,i){let n=await xN(e,Mr.dirname(t));if(!n){if(!r.exists)return;throw new Error(`${i} parent changed before commit`)}let a;try{a=await ur.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()||!rd(r.identity,a)||await ur.realpath(t)!==r.realPath)throw new Error(`${i} changed before commit`);await dm(n)}async function fm(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let r=e.expected??await h2(e.changeDir,e.file,e.label);if(r.exists&&r.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await Ne(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await m2(e.changeDir,e.file,r,e.label)}});let i=await ts(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 N_(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function b_(e){return`${JSON.stringify(e,null,2)}
|
|
232
232
|
`}function Wa(e){return lm(e)}async function At(e,t){let r=Va(e,"stateRef"),i=await ts(e,r,Jt.runStateBytes,"Native Run state",t);return i?lm(N_(i.text,"Native Run state")):null}async function rs(e,t,r){let i=lm(t);await fm({changeDir:e,file:Va(e,"stateRef"),content:b_(i),maxBytes:Jt.runStateBytes,label:"Native Run state",hooks:r})}async function dr(e,t,r){let i=Va(e,"trajectoryRef",t),n=await ts(e,i,Jt.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>Jt.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Jt.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 k_(e,t,r){return(await ts(e,Va(e,"trajectoryRef",t),Jt.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function S_(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=Va(e,"trajectoryRef",t),o=await ts(e,a,Jt.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(u2("sha256").update(o.text,"utf8").digest("hex")!==i)throw new Error("Native Run trajectory changed before repair");await fm({changeDir:e,file:a,content:r,maxBytes:Jt.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function E_(e,t,r,i){let n=Va(e,"trajectoryRef",t),a=`${JSON.stringify(r)}
|
|
233
233
|
`;if(Buffer.byteLength(a,"utf8")>Jt.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Jt.trajectoryEventBytes} bytes`);let o=await ts(e,n,Jt.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Jt.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Jt.trajectoryEvents} events`);await fm({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Jt.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:i})}async function xc(e,t,r){let i=await ts(e,Va(e,"checkpointRef",t),Jt.checkpointBytes,"Native Run checkpoint",r);return i?N_(i.text,"Native Run checkpoint"):null}async function R_(e,t,r,i){await fm({changeDir:e,file:Va(e,"checkpointRef",t),content:b_(r),maxBytes:Jt.checkpointBytes,label:"Native Run checkpoint",hooks:i})}var w2=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pm=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"};function CN(e){return v2("sha256").update(e).digest("hex")}function y2(e,t){if(!w2.test(t))throw new Error(`Invalid Native change name: ${t}`);return g2.join(Q(e,t),"trajectory.jsonl")}function N2(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 b2(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 k2(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=N2(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(`
|
|
234
234
|
`)])}catch(d){if(!b2(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:CN(t),targetHash:CN(l),tailHash:CN(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function P_(e,t){let r=y2(e,t);await T(B(e,r),r);let i=Q(e,t),n=await k_(i,Lr.trajectoryRef);return n===null?{status:"clean",file:r}:k2(r,Buffer.from(n))}async function Cc(e,t){let r=await P_(e,t);return"inspection"in r?r.inspection:r}async function hm(e,t){let r=await Cc(e,t);if(r.status!=="clean")throw new pm(r)}async function x_(e,t,r){return A(e,`repair trajectory tail for ${t}`,async()=>{let i=await P_(e,t);if(!("inspection"in i)){if(i.status==="clean")return null;throw new pm(i)}try{await S_(Q(e,t),Lr.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 Cc(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return i.inspection})}import{createHash as S2}from"node:crypto";import{promises as mm}from"node:fs";import qn from"node:path";Oe();Ht();Fe();Z();var nd=/^[a-f0-9]{64}$/u,C_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,E2=16*1024,AN=process.platform,R2=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function _c(e){return R2.has(e)}function I_(e,t){let r=qn.relative(e,t);return qn.isAbsolute(r)||r===".."||r.startsWith(`..${qn.sep}`)?null:r.replaceAll("\\","/")||"."}function j_(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function T_(e,t){if(e.length===0||j_(e)||e.includes("\\")||qn.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=qn.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function IN(e,t){return S2("sha256").update(`${e}
|
|
@@ -237,7 +237,7 @@ ${i.dev}
|
|
|
237
237
|
${i.ino}
|
|
238
238
|
${i.birthtimeMs}`)}async function A_(e,t){let r=await mm.realpath(t),i=await mm.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=AN==="win32"?qn.normalize(r).toLowerCase():r;return IN(e,n)}function P2(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 _N(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||j_(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function $_(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(_N(e.changeBranch,"Native workspace change branch"),_N(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 x2(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"||!C_.test(t.baseCommit)||typeof t.targetCommit!="string"||!C_.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");_N(t.targetBranch,"Native workspace Git target branch")}function ad(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"||!nd.test(String(t.projectRootId))||!nd.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");P2(t.capturedAt),T_(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&&!nd.test(String(t.projectRootPathId))||a&&!nd.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!nd.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&x2(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($_(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 Ac(e,t){return qn.join(Q(e,t),"workspace.json")}function C2(e,t){let r=Ac(e,t),i=B(e,r),n=I_(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:T_(n,"Native workspace file ref")}}async function O_(e,t){try{let r=C2(e,t),i=await z({root:r.root,ref:r.ref,maxBytes:E2});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function od(e,t){let r=ie(e.projectRoot),i={projectRoot:qn.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await Gt(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 sn({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 jN(e,t){let r=await O_(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:(ad(r),r.schema==="comet.native.workspace.v3"?!1:r.projectRootPathId===void 0||r.nativeRootPathId===void 0)}async function D_(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=I_(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ie(e.paths.projectRoot),i=r.isGitWorktree?er(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:er(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([__("comet.native.workspace-project-root.v2",e.paths.projectRoot),__("comet.native.workspace-native-root.v2",e.paths.nativeRoot),A_("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),A_("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&&$_(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:IN("comet.native.workspace-session.v2",`${s}
|
|
239
239
|
${c}
|
|
240
|
-
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ad(p),p}async function vm(e){let t=await D_(e),r=Ac(e.paths,e.name),i=B(e.paths,r);return await T(i,r),await ve(r,t,{containedRoot:i}),t}async function Gt(e,t){let r=await O_(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ad(r),r)}async function H_(e){return await jN(e.paths,e.name)?vm(e):null}async function za(e){ad(e.identity);let t=await D_({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")),AN==="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 sn(e){if(ad(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 za(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ie(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 F_(e,t){let r=await Gt(e,t);if(r===null)return null;let i=await sn({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}cc();_h();_h();var cd=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"},Ic=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"},jc=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"},ste=Nu("en");function pe(e,t){Tn(t);let r=Br.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Tc(e,t){let r=Q(e,t),i=Br.join(r,"schema-migration.json");await T(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await sd.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function $c(e,t){let r=Q(e,t),i=Br.join(r,"checkpoint-journal.json");await T(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await sd.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function wm(e,t=Br.dirname(e)){let r=Br.relative(t,e).split(Br.sep).join("/"),i=await z({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,gm.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 di(e,t){let r=Br.join(pe(e,t),ct);await T(e.nativeRoot,r);let i=Ch(await wm(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Tc(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 _2(e,i.state),i)}async function is(e,t){let r=Br.join(pe(e,t),ct);await T(e.nativeRoot,r);let i=Ch(await wm(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function _2(e,t){if(await Ec(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Me(e,t){let r=await di(e,t);if(r.status==="migration-required")throw new Go(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Fr(r.schema,r.minimumRuntimeVersion);return await F_(e,t),r.state}async function L_(e,t,r){let i={...t,schema:it,minimum_runtime_version:3,revision:r+1},n=await DC({expectedRevision:r,next:i,read:async()=>{let a=zt(await wm(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Ne(e,(0,gm.stringify)($n(a))),equals:(a,o)=>JSON.stringify($n(a))===JSON.stringify($n(o)),conflict:a=>new cd(t.name,r,a)});return Object.assign(t,n),n}async function ld(e,t,r,i){if(await nc(e.projectRoot),await Tc(e,t.name))throw new Go(t.name,t.schema);if(!i?.allowPendingCheckpointRecovery&&await $c(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Me(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await hm(e,t.name);let a=Br.join(pe(e,t.name),ct);return await T(e.nativeRoot,a),L_(a,t,r)}async function M_(e,t){return L_(e,t,t.revision)}async function B_(e){return zt(await wm(e))}async function A2(e){let t;try{let i=await Er({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 V_(e){let t=[];for(let r of await A2(e)){let i=await is(e,r);if(!i.state){if(await q_(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await Gt(e,r);if(!(!n&&await q_(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await sn({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await za({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}async function q_(e,t){for(let r of Vt(e.projectRoot))if(!Gi(r,e.projectRoot))try{let i=await te(r);if(!i)continue;let n=await Se(r,i.native.artifact_root),a=Br.join(n.changesDir,t),o=Br.join(a,"comet-state.yaml");try{let l=await sd.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await sd.readFile(Br.join(je(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&Gi(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await sd.access(Br.join(a,ct));let s=await Gt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await sn({paths:n,identity:s})).state==="aligned")return!0;continue}if((await za({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}ot();Fe();import{promises as U_}from"node:fs";import Nm from"node:path";fr();Oe();uc();import{promises as K_}from"node:fs";import O2 from"node:os";import fd from"node:path";function ud(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function dd(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 pr(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 Dc(e,t){return e===null?null:pr(e,t)}function Hc(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 D2(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 H2(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Fc(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function ON(e,t){if(e===null)return null;let r=pr(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function F2(e,t){let r=pr(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function DN(e,t){let r=pr(e,t);if(!fd.isAbsolute(r))throw new Error(`${t} must be absolute`);return fd.resolve(r)}function q2(e,t){let r=`Native local checks[${t}]`,i=ud(e,r);if(dd(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),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((u,d)=>pr(u,`${r}.argv[${d}]`,!0)),a=Fc(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=ON(i.startedAt,`${r}.startedAt`),s=ON(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=Hc(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=ud(i.activeProcess,`${r}.activeProcess`),d=Fc(u.status,["starting","running"],`${r}.activeProcess.status`);if(dd(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:Hc(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:pr(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:pr(i.id,`${r}.id`),name:pr(i.name,`${r}.name`),operationId:pr(i.operationId,`${r}.operationId`),status:a,repeatable:H2(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Hc(i.executionCount,`${r}.executionCount`),argv:n,cwd:DN(i.cwd,`${r}.cwd`),exitCode:D2(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:pr(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Fc(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:pr(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function HN(e){let t="Native local execution state",r=ud(e,t);if(dd(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Wu)throw new Error(`Native local execution schema must be ${Wu}`);let i=ud(r.workspace,"Native local workspace");dd(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ud(r.execution,"Native local execution");dd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=ON(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:pr(o.operationId,"Native local execution.operationId"),stage:Fc(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Fc(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Dc(o.executionId,"Native local execution.executionId"),status:Fc(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Hc(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:F2(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Hc(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:pr(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(q2);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:Wu,change:pr(r.change,"Native local change"),basedOnStateVersion:Hc(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Dc(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Dc(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Dc(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Dc(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:DN(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:DN(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Dc(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:pr(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function Te(e){return HN({schema:Wu,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:fd.resolve(e.projectRoot),worktreeRoot:fd.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:O2.hostname()},execution:null,checks:[]})}async function lt(e){let t;try{t=await K_.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 HN(r)}function qc(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}async function le(e,t,r={}){let i=HN(t);await K_.mkdir(fd.dirname(e),{recursive:!0}),await ve(e,i,r)}async function ym(e){let t=null,r=null;try{t=await lt(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=Te(e);return await le(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}sr();Z();var cn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y_="comet-state.yaml",X_="state.json";function X(e,t){if(!cn.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Nm.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function gt(e,t){return Nm.join(X(e,t),Y_)}function G(e,t){return Nm.join(je(e,t),X_)}async function Ae(e,t){try{let r=await U_.readFile(gt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Q_(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Ke(e){return oE(e)}function bm(e,t){let r=ie(t);if(!r.isGitWorktree||r.currentBranch===null||er(t,r.currentBranch)===null)return null;if(!Oc(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}function Z_(e,t){if(!t)return;let r=ie(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 O(e,t){return qt(gt(e,t))}async function Be(e){let t=await en({file:gt(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=Nm.join(X(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await U_.rm(r,{force:!0})}return t}async function ns(e){let t=await O(e.paths,e.name),r=G(e.paths,e.name);try{let i=await lt(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"}}}Oe();import{createHash as DG}from"node:crypto";import{promises as Ur}from"node:fs";import Ut from"node:path";To();import{promises as FN}from"fs";import tA from"path";Ht();ci();Z();var rA=["outcome","scope","nonGoals","acceptanceExamples"],eA=[...rA,"constraints","decisions","openQuestions","verificationExpectations"],L2=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],M2=new Set(["nonGoals","decisions","openQuestions"]),iA={maxFileBytes:xg};function nA(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
240
|
+
${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return ad(p),p}async function vm(e){let t=await D_(e),r=Ac(e.paths,e.name),i=B(e.paths,r);return await T(i,r),await ve(r,t,{containedRoot:i}),t}async function Gt(e,t){let r=await O_(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ad(r),r)}async function H_(e){return await jN(e.paths,e.name)?vm(e):null}async function za(e){ad(e.identity);let t=await D_({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")),AN==="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 sn(e){if(ad(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 za(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ie(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 F_(e,t){let r=await Gt(e,t);if(r===null)return null;let i=await sn({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}cc();_h();_h();var cd=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"},Ic=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"},jc=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"},cte=Nu("en");function pe(e,t){Tn(t);let r=Br.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Tc(e,t){let r=Q(e,t),i=Br.join(r,"schema-migration.json");await T(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await sd.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function $c(e,t){let r=Q(e,t),i=Br.join(r,"checkpoint-journal.json");await T(q(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await sd.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function wm(e,t=Br.dirname(e)){let r=Br.relative(t,e).split(Br.sep).join("/"),i=await z({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,gm.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 di(e,t){let r=Br.join(pe(e,t),ct);await T(e.nativeRoot,r);let i=Ch(await wm(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await Tc(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 _2(e,i.state),i)}async function is(e,t){let r=Br.join(pe(e,t),ct);await T(e.nativeRoot,r);let i=Ch(await wm(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function _2(e,t){if(await Ec(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Me(e,t){let r=await di(e,t);if(r.status==="migration-required")throw new Go(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Fr(r.schema,r.minimumRuntimeVersion);return await F_(e,t),r.state}async function L_(e,t,r){let i={...t,schema:it,minimum_runtime_version:3,revision:r+1},n=await DC({expectedRevision:r,next:i,read:async()=>{let a=zt(await wm(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>Ne(e,(0,gm.stringify)($n(a))),equals:(a,o)=>JSON.stringify($n(a))===JSON.stringify($n(o)),conflict:a=>new cd(t.name,r,a)});return Object.assign(t,n),n}async function ld(e,t,r,i){if(await nc(e.projectRoot),await Tc(e,t.name))throw new Go(t.name,t.schema);if(!i?.allowPendingCheckpointRecovery&&await $c(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Me(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await hm(e,t.name);let a=Br.join(pe(e,t.name),ct);return await T(e.nativeRoot,a),L_(a,t,r)}async function M_(e,t){return L_(e,t,t.revision)}async function B_(e){return zt(await wm(e))}async function A2(e){let t;try{let i=await Er({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 V_(e){let t=[];for(let r of await A2(e)){let i=await is(e,r);if(!i.state){if(await q_(e,r))continue;t.push(r);continue}if(i.state.archived)continue;let n=await Gt(e,r);if(!(!n&&await q_(e,r))){if(n?.schema==="comet.native.workspace.v3"){if((await sn({paths:e,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await za({paths:e,identity:n})).state==="drifted")continue;t.push(r)}}return t}async function q_(e,t){for(let r of Vt(e.projectRoot))if(!Gi(r,e.projectRoot))try{let i=await te(r);if(!i)continue;let n=await Se(r,i.native.artifact_root),a=Br.join(n.changesDir,t),o=Br.join(a,"comet-state.yaml");try{let l=await sd.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await sd.readFile(Br.join(je(n,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&Gi(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await sd.access(Br.join(a,ct));let s=await Gt(n,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await sn({paths:n,identity:s})).state==="aligned")return!0;continue}if((await za({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}ot();Fe();import{promises as U_}from"node:fs";import Nm from"node:path";fr();Oe();uc();import{promises as K_}from"node:fs";import O2 from"node:os";import fd from"node:path";function ud(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function dd(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 pr(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 Dc(e,t){return e===null?null:pr(e,t)}function Hc(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 D2(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 H2(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Fc(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function ON(e,t){if(e===null)return null;let r=pr(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function F2(e,t){let r=pr(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function DN(e,t){let r=pr(e,t);if(!fd.isAbsolute(r))throw new Error(`${t} must be absolute`);return fd.resolve(r)}function q2(e,t){let r=`Native local checks[${t}]`,i=ud(e,r);if(dd(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),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((u,d)=>pr(u,`${r}.argv[${d}]`,!0)),a=Fc(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=ON(i.startedAt,`${r}.startedAt`),s=ON(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=Hc(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=ud(i.activeProcess,`${r}.activeProcess`),d=Fc(u.status,["starting","running"],`${r}.activeProcess.status`);if(dd(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:Hc(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:pr(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:pr(i.id,`${r}.id`),name:pr(i.name,`${r}.name`),operationId:pr(i.operationId,`${r}.operationId`),status:a,repeatable:H2(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Hc(i.executionCount,`${r}.executionCount`),argv:n,cwd:DN(i.cwd,`${r}.cwd`),exitCode:D2(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:pr(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:Fc(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:pr(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function HN(e){let t="Native local execution state",r=ud(e,t);if(dd(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Wu)throw new Error(`Native local execution schema must be ${Wu}`);let i=ud(r.workspace,"Native local workspace");dd(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ud(r.execution,"Native local execution");dd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=ON(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:pr(o.operationId,"Native local execution.operationId"),stage:Fc(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Fc(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Dc(o.executionId,"Native local execution.executionId"),status:Fc(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Hc(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:F2(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Hc(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:pr(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(q2);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:Wu,change:pr(r.change,"Native local change"),basedOnStateVersion:Hc(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Dc(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Dc(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Dc(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Dc(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:DN(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:DN(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Dc(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:pr(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function Te(e){return HN({schema:Wu,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:fd.resolve(e.projectRoot),worktreeRoot:fd.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:O2.hostname()},execution:null,checks:[]})}async function lt(e){let t;try{t=await K_.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 HN(r)}function qc(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}async function le(e,t,r={}){let i=HN(t);await K_.mkdir(fd.dirname(e),{recursive:!0}),await ve(e,i,r)}async function ym(e){let t=null,r=null;try{t=await lt(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=Te(e);return await le(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}sr();Z();var cn=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Y_="comet-state.yaml",X_="state.json";function X(e,t){if(!cn.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=Nm.join(e.changesDir,t);if(!q(e.changesDir,r))throw new Error("Native change path escaped");return r}function gt(e,t){return Nm.join(X(e,t),Y_)}function G(e,t){return Nm.join(je(e,t),X_)}async function Ae(e,t){try{let r=await U_.readFile(gt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Q_(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Ke(e){return oE(e)}function bm(e,t){let r=ie(t);if(!r.isGitWorktree||r.currentBranch===null||er(t,r.currentBranch)===null)return null;if(!Oc(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}function Z_(e,t){if(!t)return;let r=ie(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 O(e,t){return qt(gt(e,t))}async function Be(e){let t=await en({file:gt(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=Nm.join(X(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await U_.rm(r,{force:!0})}return t}async function ns(e){let t=await O(e.paths,e.name),r=G(e.paths,e.name);try{let i=await lt(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"}}}Oe();import{createHash as DG}from"node:crypto";import{promises as Ur}from"node:fs";import Ut from"node:path";To();import{promises as FN}from"fs";import tA from"path";Ht();ci();Z();var rA=["outcome","scope","nonGoals","acceptanceExamples"],eA=[...rA,"constraints","decisions","openQuestions","verificationExpectations"],L2=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],M2=new Set(["nonGoals","decisions","openQuestions"]),iA={maxFileBytes:xg};function nA(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
241
241
|
`).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 B2(e,t){let r=tA.resolve(e,...t.split(/[\\/]/u));if(!q(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await FN.realpath(e),n=await FN.realpath(r);if(!q(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await FN.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function Lc(e){return{valid:e.length===0,findings:e}}function qN(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function V2(e){return qN(e).trim()}function km(e){let t=V2(e).split(/\r?\n/u),r=[],i=!1;for(let n of t){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
|
|
242
242
|
`).trim()}function W2(e){let t=km(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function aA(e){let t=km(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function oA(e,t){let r=[];return km(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):aA(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),Lc(r)}function LN(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 pd(e,t,r={}){let i=[],n;try{n=(await z({root:e,ref:t,maxBytes:iA.maxFileBytes})).text}catch(s){return Lc([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of nA(n))a.set(rh(s)??s,c);for(let s of eA)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?eA:rA;for(let s of o){let c=a.get(s)??"";km(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):aA(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!M2.has(s)&&W2(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return LN(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Lc(i)}async function MN(e,t){let r=[],i;try{i=(await z({root:e,ref:t,maxBytes:iA.maxFileBytes})).text}catch(a){return Lc([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of nA(i))n.set(dx(a)??a,o);for(let a of L2)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 Lc(r)}function Ja(e,t){return tA.join(e.specsDir,t,"spec.md")}async function sA(e,t){let r=[],i=pe(e,t.name);for(let n of t.spec_changes){let a=Ja(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await si(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 B2(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return Lc(r)}Ht();Qe();var LI=Ji(Ri(),1);import{promises as qI}from"node:fs";import Gr from"node:path";fr();Ht();Qe();ot();Z();sr();Rm();Rm();Ya();ln();import{randomUUID as GJ}from"node:crypto";import{promises as II}from"node:fs";import yt from"node:path";import Om from"node:path";function Ed(...e){if(e.length===0)return Om.resolve();if(Om.win32.isAbsolute(e[0])){let t=Om.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Om.resolve(...e)}fr();$u();Oe();Qe();Vc();Fe();Z();ib();Ya();ln();ls();fr();import{promises as jd}from"node:fs";import xr from"node:path";ot();ls();zo();Z();var Xa=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function OA(e,t){let r=xr.relative(e,t);return r===""||!xr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xr.sep}`)}function TA(e){return JSON.stringify(e.native)}async function Mm(e,t){let r=await te(e);if(r&&t){if(TA(r)!==TA(t))throw new Error(`Native worktree configuration differs from the source project: ${xr.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Dr(e,t),await Lm(e),!0):!1}async function xz(e,t){if(!OA(e,t))return!1;let i=`/${xr.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=_(e,["rev-parse","--git-common-dir"]),a=xr.resolve(e,n),o=xr.join(a,"info","exclude"),s="";try{s=await jd.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await jd.mkdir(xr.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
243
243
|
`)?"":`
|
|
@@ -316,55 +316,55 @@ ${qi(e.verification.summary)}
|
|
|
316
316
|
`)}
|
|
317
317
|
`}function FG(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function qG(e){let t=[],r=!1;for(let i of qN(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!FG(n[1]??"")})}function fj(e,t){let r=e.map(({code:i,message:n,path:a})=>`- ${i}${a?` (${a})`:""}: ${n}`).join(`
|
|
318
318
|
`);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
|
|
319
|
-
`)}async function tf(e){let t=X(e.paths,e.state.name),r=[...(await pd(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:l})=>l!=="remove"),o=e.state.spec_changes.filter(({operation:l})=>l!=="remove"),s=new Set(a.map(({capability:l})=>l));if(e.specChanges!==void 0)for(let l of o)s.has(l.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${l.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${l.capability}/spec.md`});let c=n.length>0&&n.every(({operation:l})=>l==="remove");a.length===0&&o.length===0&&!c&&!qG(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let l of a){let u=`specs/${l.capability}/spec.md`;if(l.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:l.source??u});continue}try{let d=(await z({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...oA(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function av(e){let t=await tf(e);if(!t.valid)throw new Error(fj(t.findings,{change:e.state.name,phase:e.state.phase}))}function mi(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Mb(e){return A(e.paths,`create portable change ${e.name}`,async()=>{if(!cn.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await te(e.paths.projectRoot)===null&&await Dr(e.paths.projectRoot,e.initialProjectConfig),Z_(e.paths.projectRoot,e.workspaceBinding);let t=(await V_(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Ic(e.workspaceBinding?.isolation??"current",t);let r=X(e.paths,e.name),i=je(e.paths,e.name);await Promise.all([T(e.paths.nativeRoot,r),T(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await Ur.mkdir(e.paths.changesDir,{recursive:!0}),await Ur.mkdir(r,{recursive:!1}),n=!0,await Ur.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await Ur.mkdir(i,{recursive:!1}),a=!0,await Ur.mkdir(Ut.join(r,"specs"),{recursive:!0}),await Ne(Ut.join(r,"brief.md"),Nu(e.language));let o=Xy({name:e.name,language:e.language,workspace:Q_(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await pc(gt(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await le(G(e.paths,e.name),Te({portableState:o,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await Ur.rm(i,{recursive:!0,force:!0}),n&&await Ur.rm(r,{recursive:!0,force:!0}),o}})}async function rf(e){let t=X(e.paths,e.state.name),r=Ut.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Ur.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(!cn.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=Ut.join(t,...s.split("/")),l=await Ur.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Ut.join(e.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let v=await Ur.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=rt((await z({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let p=`specs/${o.name}/${Ys}`,h=Ut.join(t,...p.split("/")),m={};try{let v=await Ur.lstat(h);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let g=await z({root:t,ref:p,maxBytes:null,includeHash:!1}),w=Pi(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let k=f??rt(""),b=e.state.spec_changes.find(R=>R.capability===o.name);if(b?.delta_source!==void 0){if(b.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==k)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);m={delta_source:p,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...m})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function ov(e){let t=X(e.paths,e.state.name),r=await rf(e),i=[...r],n=[],a=[];for(let[s,c]of r.entries()){if(!c.delta_source||!c.source)continue;let l=await z({root:t,ref:c.delta_source,maxBytes:null,includeHash:!1}),u=Pi(l.text),d="";try{d=(await z({root:e.paths.specsDir,ref:`${c.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(w){if(w.code!=="ENOENT")throw w}let f=yu({currentMarkdown:d,delta:u});if(!f.rebased)continue;let p=th(d),h=Object.fromEntries(p.requirements.map(w=>[w.id,rt(w.raw)])),m=u.independent_requirements===void 0?void 0:Object.fromEntries(Object.keys(u.independent_requirements).flatMap(w=>{let k=p.requirements.find(b=>b.id===w);return k?[[w,rt(k.raw)]]:[]})),v={...u,base_hash:rt(d),base_version:u.base_version+1,legacy_hash:jo(d),base_requirements:h,...m===void 0?{}:{independent_requirements:m}},g=await z({root:t,ref:c.source,maxBytes:null,includeHash:!1});a.push({index:s,spec:c,originalDeltaText:l.text,originalSourceText:g.text,deltaText:eh(v),sourceText:f.markdown}),i[s]={...c,base_hash:v.base_hash},n.push(c.capability)}if(n.length===0)return{state:e.state,rebased:!1,capabilities:n};let o=!1;try{for(let d of a)await Ne(Ut.join(t,...d.spec.delta_source.split("/")),d.deltaText,{containedRoot:e.paths.nativeRoot}),await Ne(Ut.join(t,...d.spec.source.split("/")),d.sourceText,{containedRoot:e.paths.nativeRoot});let s={...e.state,spec_changes:i},c=await ol({paths:e.paths,state:s,specChanges:i});if(!Th(e.state.acceptance,c.acceptance))throw new Error("Native delta rebase changed the confirmed acceptance scope; explicit Shape confirmation is required");let l=await It({changeDir:t,acceptanceIds:c.acceptance.map(({id:d})=>d),validation:Vr({...s,acceptance:c.acceptance})}),u=await Be({paths:e.paths,previous:e.state,next:{...e.state,state_version:e.state.state_version+1,spec_changes:i,shape_confirmation_hash:sl({formalHash:c.formalHash,childrenHash:l?.hash??null,coordinationMode:e.state.coordination_mode})}});return o=!0,{state:u,rebased:!0,capabilities:n}}catch(s){if(!o)for(let c of a)await Ne(Ut.join(t,...c.spec.delta_source.split("/")),c.originalDeltaText,{containedRoot:e.paths.nativeRoot}),await Ne(Ut.join(t,...c.spec.source.split("/")),c.originalSourceText,{containedRoot:e.paths.nativeRoot});throw s}}async function ol(e){let t=X(e.paths,e.state.name),r=await z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(LN(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await z({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await z({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=Pi(u.text);c=ox(s.text,d);let f="";try{f=(await z({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(rt(f)===d.base_hash){let p=py({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(rt(s.text)!==p.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=j("comet.native.shape-artifact-content.v1",nv(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:j("comet.native.shape-artifact-content.v1",nv(s.text)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await z({root:t,ref:Lb,maxBytes:65536,includeHash:!1}),s=lj(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=Ut.relative(e.paths.projectRoot,Ut.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(Ut.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=j("comet.native.shape-artifact-content.v1",nv(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:jh({briefMarkdown:r.text,specs:i}),formalHash:j("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:j("comet.native.shape-artifact-content.v1",nv(r.text))},specs:n,association:{source:Lb,contentHash:a}})}}function sl(e){return j("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Bb(e){return A(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(mi({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 rf({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await av({paths:e.paths,state:t,specChanges:r});let i=await ol({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await It({changeDir:X(e.paths,t.name),acceptanceIds:n.map(({id:f})=>f),validation:Vr({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await $m(e.paths,t.name);let f=bm(t.workspace,e.paths.projectRoot);if(f===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=pt({...t,workspace:f},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:we(`Native workspace bound to branch ${f.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await Xd(X(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let c=s?e.coordinationMode??t.coordination_mode:void 0;if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let l={...o,spec_changes:r,shape_confirmation_hash:sl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})};delete l.children_contract_hash,delete l.coordination_mode,s&&(l.coordination_mode=c);let u=zI({state:l,acceptance:n.map(f=>({...f}))});e.enforceDocumentConstraints===!0&&(u.document_constraints_version=1),a&&(u.children_contract_hash=al({acceptance:u.acceptance,children:a.contract}));let d=await Be({paths:e.paths,previous:t,next:u});return await le(G(e.paths,t.name),Te({portableState:d,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),d})}async function Mi(e){if(e.state.document_constraints_version===1){let l=await tf(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await rf(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.delta_source===d.delta_source&&l.base_hash===d.base_hash&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await ol({...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(!Th(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await It({changeDir:X(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Vr({...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&&sl({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?al({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 sv(e){return A(e.paths,`recover pending Shape confirmation ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.next_action!=="confirm-shape")return{state:t,repaired:!1,reason:null};let r=await Mi({paths:e.paths,state:t});if(!r.drifted)return{state:t,repaired:!1,reason:null};let i=r.reason??"Native confirmed requirements changed";return{state:await Zn({paths:e.paths,state:t,reason:i,keepFailureBudget:!0}),repaired:!0,reason:i}})}async function vr(e){let t=await Mi(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Zn({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Vb(e){return A(e.paths,`sync spec references ${e.name}`,async()=>{let t=await O(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(!cn.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await vr({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:h,operation:m})=>h===e.capability&&m!=="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(h=>!t.acceptance.some(m=>m.id===h))||t.acceptance.some(({source:h,id:m})=>h===r.source&&!i.has(m)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:h,to:m})=>!/^[A-Za-z0-9_./#%-]+$/u.test(h)||!/^[A-Za-z0-9_./#%-]+$/u.test(m)||h===m)||new Set(e.replacements.map(({from:h})=>h)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=X(e.paths,t.name),a=await z({root:n,ref:r.source,maxBytes:null,includeHash:!1}),o=new Map(e.replacements.map(({from:h,to:m})=>[h,m])),s=new Set,c=null,l=!1,u=a.text.split(/(?<=\n)/u).map(h=>{let m=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(h.trimEnd());return m?(c?m[1][0]===c.marker&&m[1].length>=c.length&&!m[2].trim()&&(c=null):c={marker:m[1][0],length:m[1].length},h):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(h)?h:(h.includes("<!--")&&(l=!0),l?(h.includes("-->")&&(l=!1),h):c||/^(?: {4}|\t)/u.test(h)||h.includes("`")?h:h.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(v,g,w)=>{let k=o.get(w);return k?(s.add(w),`[${g}](${k})`):v}))}).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=Ut.join(n,r.source);await Ne(d,u,{containedRoot:e.paths.nativeRoot});let f=!1,p=null;try{let h=await ol({paths:e.paths,state:t,specChanges:t.spec_changes});if(!Th(t.acceptance,h.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let m=y=>DG("sha256").update(y).digest("hex"),v=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:m(a.text),afterHash:m(u),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=m(v),w=await tl({paths:e.paths,name:t.name,hash:g,text:v,onCreated:()=>{p=g}}),k={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},b=t.phase==="build"?{...k,state_version:t.state_version+1,acceptance:t.acceptance.map(y=>i.has(y.id)?{...y,result:"pending",reason:null}:y)}:Yn({state:k,reason:`Spec reference sync: ${e.reason}`});b=pt(b,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:we(`Spec reference sync by ${e.actor}: ${e.reason}; ${w}`),completed_at:new Date().toISOString()}),b.shape_confirmation_hash=sl({formalHash:h.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let R=await Be({paths:e.paths,previous:t,next:b});return f=!0,await le(G(e.paths,t.name),Te({portableState:R,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),R}catch(h){if(!f)try{(await O(e.paths,t.name)).state_version===t.state_version&&(await Ne(d,a.text,{containedRoot:e.paths.nativeRoot}),p&&await gb({paths:e.paths,name:t.name,hash:p}))}catch{}throw h}})}async function Wb(e){if(!cn.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return A(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await O(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 Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function zb(e){return A(e.paths,`disassociate portable capability ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(mi({state:t,expected:e.expectedContinuation,action:"disassociate-capability"}),t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=Ut.join(X(e.paths,e.name),Lb),i;try{i=await Ur.lstat(r)}catch(n){if(n.code==="ENOENT")return t;throw n}if(!i.isFile()||i.isSymbolicLink())throw new Error("Native capability association must be a regular file");return await Ur.rm(r),Zn({paths:e.paths,state:t,reason:"Capability association revoked through comet native spec disassociate"})})}async function cv(e){return A(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await O(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 Be({paths:e.paths,previous:t,next:r});return await le(G(e.paths,t.name),Te({portableState:i,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await Li({file:Ut.join(X(e.paths,t.name),"verification.md"),state:i}),i})}async function Ns(e){return A(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await O(e.paths,e.name);if(mi({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:Zn({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function Zn(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:we(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:e.keepFailureBudget?t.loop.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 Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}ot();Fe();Ya();ln();sr();$a();async function Jb(e){return A(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(mi({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 vr({paths:e.paths,state:t});let r=await rf({paths:e.paths,state:t}),i=await ol({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await It({changeDir:X(e.paths,t.name),acceptanceIds:n.map(({id:g})=>g),validation:Vr({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await $m(e.paths,t.name);let g=bm(t.workspace,e.paths.projectRoot);if(g===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=pt({...t,workspace:g},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:we(`Native workspace bound to branch ${g.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await Xd(X(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=t.coordination_mode;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=sl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let g=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Zn({paths:e.paths,state:t,reason:g,keepFailureBudget:!0}),new Error(`${g}; Native change returned to Shape and requires confirmation`)}let u=WI({state:{...o,spec_changes:r},acceptance:n.map(g=>({...g}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=al({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let g=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(g?.outcome==="fail"&&g.unresolved_ids.length>0){let w=await nt({paths:e.paths,state:u}),k=new Map((w?.children??[]).map(({name:y,status:S})=>[y,S])),b=new Set(a.contract.children.filter(({name:y})=>{let S=k.get(y);return S!=="done"&&S!=="integrated"&&S!=="archived"}).flatMap(({covers:y})=>y)),R=g.unresolved_ids.filter(y=>!b.has(y));if(R.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${R.join(", ")}`)}}let d=null,f=a?.contract.schema==="comet.native.children.v2"?await J(e.paths,t.name):null,p=null,h=null;if(a?.contract.schema==="comet.native.children.v2"){if(p=o.workspace.change_branch??o.workspace.target_branch,!p)throw new Error("Native Supervisor v2 requires a target branch");if(h=er(e.paths.projectRoot,p),!h)throw new Error(`Native Supervisor target branch has no commit: ${p}`);f||(f=await Yd({paths:e.paths,parent:t.name,targetBranch:p,contract:a.contract})),f||(d=await Cb({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:p,sourceConfig:await te(e.paths.projectRoot)}))}let m=a?.contract.schema==="comet.native.children.v2"&&p&&h?f?GN({state:f,contract:a.contract}):d?Nd({parent:u.name,targetBranch:p,targetCommit:h,integrationBranch:d.binding.changeBranch,integrationWorktree:d.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!m)throw new Error("Native Supervisor integration state is unavailable");let v=await Be({paths:e.paths,previous:t,next:u});return await le(G(e.paths,t.name),Te({portableState:v,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),m&&await oe(e.paths,m),v})}fr();$u();Qe();Vc();import{createHash as vj,randomUUID as gj}from"node:crypto";import{promises as hn}from"node:fs";import oo from"node:os";import K from"node:path";Fe();$a();Z();async function Gb(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}function dv(e,t){let r=K.relative(K.resolve(e),K.resolve(t));if(K.isAbsolute(r)||r===".."||r.startsWith(`..${K.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(K.sep).join("/");return Pd(e,i),i}function lv(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Bc({id:e.id,name:e.name,executable:r,argv:i,cwdRef:dv(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function dl(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:dv(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function wj(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||K.resolve(e.workspace.projectRoot)!==K.resolve(r)||K.resolve(e.workspace.worktreeRoot)!==K.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==oo.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>lv(o,r)===Bc(t[s]))}function pj(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>lv(i,r)===Bc(t[n]))}async function ul(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await oc(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await oc(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function hj(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function uv(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:Pd(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function yj(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 Nj(e,t,r,i)}function Nj(e,t,r,i){return{...uv(t,r,i),executionCount:e.executionCount}}function bj(e){return vj("sha256").update(e).digest("hex")}async function of(e){let t=await hn.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=vj("sha256"),i=await hn.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(LG);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await hn.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var kj=2e4,Sj=1024*1024*1024,LG=65535,Ej=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],MG=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),Kb=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],Rj=new Set(["comet-state.yaml","children.yaml","verification.md"]);function ll(e,t){if(!t)return[...Kb];let r=K.relative(e,t).replaceAll("\\","/");if(K.isAbsolute(r)||r===".."||r.startsWith("../"))return[...Kb];let i=r===""?"":`${r}/`;return[...Kb,...["changes","archive"].flatMap(n=>[...Rj].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function Ub(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!Rj.has(K.basename(i)))return!1;let n=K.resolve(t,...i.split("/")),a=K.relative(K.resolve(r),n);if(K.isAbsolute(a)||a===".."||a.startsWith(`..${K.sep}`))return!1;let[,o]=a.split(K.sep);return a.startsWith(`comet${K.sep}`)&&(o==="changes"||o==="archive")}function cl(){return{complete:!1,files:[]}}function BG(e){let t=e==="."?"":`${e}/`;return Ej.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function Pj(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function xj(e,t,r){let i=[...new Set(t.map(({cwdRef:s})=>s))];if(i.length===0)return{complete:!0,files:[]};let n;try{n=[...new Set(_(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...i.flatMap(BG)]).split("\0").filter(Boolean).map(s=>s.replaceAll("\\","/")))].sort()}catch{return cl()}if(n.length>kj)return cl();let a=[],o=0;for(let s of n){if(Ub(s,e,r))continue;let c=K.resolve(e,...s.split("/"));if(!q(e,c)||Pj(s))return cl();try{let l=await hn.lstat(c);if(!l.isFile()||o+l.size>Sj)return cl();let{digest:u,size:d}=await of(c);o+=d,a.push({path:s,digest:u,size:d})}catch{return cl()}}return{complete:!0,files:a}}async function VG(e,t,r){let i=[...new Set(t.map(({cwdRef:c})=>c))],n=new Map,a=0,o=c=>Ej.includes(c),s=async(c,l,u)=>{let d;try{d=await hn.readdir(c,{withFileTypes:!0})}catch{return!1}d.sort((f,p)=>f.name.localeCompare(p.name,"en"));for(let f of d){let p=l?`${l}/${f.name}`:f.name;if(Ub(p,e,r)||f.isDirectory()&&MG.has(f.name))continue;let h=K.join(c,f.name);if(f.isDirectory()){if(!await s(h,p,u||o(f.name)))return!1;continue}if(u){if(Pj(p)||!f.isFile())return!1;try{let m=await hn.lstat(h);if(a+m.size>Sj)return!1;let{digest:v,size:g}=await of(h);if(a+=g,n.set(p,{path:p,digest:v,size:g}),n.size>kj)return!1}catch{return!1}}}return!0};for(let c of i){let l=Pd(e,c);if(!await s(l,c==="."?"":c,o(K.basename(l))))return cl()}return{complete:!0,files:[...n.values()].sort((c,l)=>c.path.localeCompare(l.path,"en"))}}function Yb(e,t){return j("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:K.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:bj(t)})}async function WG(e){let t={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},r=!1;try{t.head=_(e.projectRoot,["rev-parse","HEAD"]),r=!0,t.branch=_(e.projectRoot,["branch","--show-current"]),t.status=_(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...ll(e.projectRoot,e.managedArtifactRoot)]);let i=_(e.projectRoot,["diff","--name-only","-z","HEAD","--",...ll(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.diff=await Gb(i,4,async a=>{let o=K.resolve(e.projectRoot,...a.split("/"));try{let{digest:s}=await of(o);return{path:a,digest:s}}catch{return{path:a,digest:null}}}),t.diff.some(({digest:a})=>a===null)&&(t.complete=!1),t.stagedDiff=bj(_(e.projectRoot,["ls-files","--stage","-z","--",...ll(e.projectRoot,e.managedArtifactRoot)])),t.submodules=_(e.projectRoot,["submodule","status","--recursive"]);let n=_(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...ll(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.untracked=await Gb(n,4,async a=>{let o=K.resolve(e.projectRoot,...a.split("/"));try{let{digest:s,size:c}=await of(o);return{path:a,digest:s,size:c}}catch{return{path:a,digest:null,size:null}}}),t.untracked.some(({digest:a})=>a===null)&&(t.complete=!1),t.ignored=await xj(e.projectRoot,e.plans,e.managedArtifactRoot),t.ignored.complete||(t.complete=!1)}catch{r?t.complete=!1:(t.capture="physical-tree",t.physical=await VG(e.projectRoot,e.plans,e.managedArtifactRoot),t.complete=t.physical.complete)}return j("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:i,source:n,text:a})=>({id:i,source:n,text:a})),git:t,projectRoot:K.resolve(e.projectRoot),machineId:oo.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([i])=>Cj.has(i.toUpperCase())).map(([i,n])=>[i,n??null]).sort(([i],[n])=>i.localeCompare(n))})}var Cj=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function zG(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function JG(){return Object.entries(process.env).filter(([e])=>Cj.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function mj(e){try{let t=_(e.projectRoot,["rev-parse","HEAD"]),r=_(e.projectRoot,["branch","--show-current"]),i=_(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...ll(e.projectRoot,e.managedArtifactRoot)]),n=_(e.projectRoot,["ls-files","--stage","-z","--",...ll(e.projectRoot,e.managedArtifactRoot)]);if(t===null||i===null)return null;let a=[];for(let s of Ln(e.projectRoot).filter(c=>!Ub(c,e.projectRoot,e.managedArtifactRoot))){let c=K.resolve(e.projectRoot,...s.split("/")),l=null;try{l=(await of(c)).digest}catch{return null}a.push({path:s,digest:l})}a.sort((s,c)=>s.path.localeCompare(c.path,"en"));let o=await xj(e.projectRoot,e.plans??[],e.managedArtifactRoot);return o.complete?j("comet.native.check-input-gate.v1",{candidateId:e.candidateId,head:t,branch:r,status:i,staged:n,workingTree:a,ignored:o,projectRoot:K.resolve(e.projectRoot),machineId:oo.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:JG()}):null}catch{return null}}function so(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`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:we(i),argv_display:xd(r.argv.slice(1)).map(n=>we(n)),argv_truncated:!1,cwd_ref:dv(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:zG(r)}})}function GG(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function bs(e){if(e.local===null||e.local.change!==e.state.name)return Te({portableState:e.state,projectRoot:e.projectRoot,branch:Ke(e.projectRoot)});let t=e.local.execution?.operationId??gj();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 co(e){try{let t=await lt(G(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function sf(e){let t=await co({paths:e.paths,state:e.state}),r=Xm({state:e.state,summary:e.summary}),i=await Be({paths:e.paths,previous:e.state,next:r});return await le(G(e.paths,e.state.name),bs({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function KG(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await T(t,K.resolve(t,...r.log.split(/[\\/]/u)));if(!(await hn.stat(i)).isFile())return!1;let n=await hn.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==Yb(r,n))return!1}catch{return!1}}return!0}async function UG(e){return A(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(await vr({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=Ke(e.projectRoot),i=G(e.paths,t.name),n=(await ym({file:i,portableState:t,projectRoot:e.projectRoot,branch:r,containedRoot:e.paths.runtimeDir})).state,a=await mj({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),o=await mj({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:[],managedArtifactRoot:e.paths.artifactRoot}),s=a===null,l=a!==null&&n.inputFingerprint!==null&&n.inputFingerprintGate===a&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.machineId===oo.hostname()?n.inputFingerprint:await WG({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),u=je(e.paths,t.name),d=await KG(n,u),f=n.checks.every(E=>E.status==="passed"),p=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),h=n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===oo.hostname()&&n.inputFingerprint===l,m=o!==null&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===oo.hostname(),v=m&&n.inputFingerprint!==null&&n.inputFingerprint!==l,g=wj(n,e.plans,e.projectRoot,t,l,r)||m&&pj(n,e.plans,e.projectRoot),w=n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===oo.hostname(),k=h&&f&&!d;if(p&&p.size===0)throw new Error("Native check retry list must contain at least one ID");if(!h&&n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&n.execution.status==="running"){let E=await ul(n);if(E!=="orphaned")throw new Error(E==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");n=hj(n),await le(i,n,{containedRoot:e.paths.runtimeDir})}if(!h&&w&&n.inputFingerprint!==null&&(n.execution!==null||n.checks.length>0)){let E=n.inputFingerprint!==l;if(!(s&&!E||v)){let N=Yn({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),P=await Be({paths:e.paths,previous:t,next:N});throw await le(i,Te({portableState:P,projectRoot:e.paths.projectRoot,branch:r}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!h&&!m){let E=Te({portableState:t,projectRoot:e.projectRoot,branch:r});await le(i,E,{containedRoot:e.paths.runtimeDir}),n=E}let b=pj(n,e.plans,e.projectRoot);if(n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&b&&g){let E=n.execution;if(E.status==="running"){let P=await ul(n);if(P!=="orphaned")throw new Error(P==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");n=hj(n),await le(i,n,{containedRoot:e.paths.runtimeDir}),E=n.execution}let N=n.checks.filter(P=>P.status==="interrupted");if(N.length===0&&E.status==="completed"&&f&&!k&&!v){let P=new Map(e.plans.map(({id:C,name:x})=>[C,x]));return{kind:"reuse",state:t,checks:so({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(N.length===0&&E.status==="completed"&&!f&&!k&&!v)throw new Error(`Native check plan contains a failed check (${n.checks.filter(({status:P})=>P==="failed").map(({id:P})=>P).join(", ")}); submit a new Builder candidate`);if(N.length>0&&N.some(P=>!P.repeatable)&&!k){let P=Yn({state:t,reason:`A non-repeatable Runtime check was interrupted (${N.filter(x=>!x.repeatable).map(({id:x})=>x).join(", ")}); a new Builder candidate is required before it can run again.`}),C=await Be({paths:e.paths,previous:t,next:P});throw await le(G(e.paths,t.name),Te({portableState:C,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${N.find(x=>!x.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(N.length>0&&p===null&&!k&&!v){let P=new Map(e.plans.map(({id:C,name:x})=>[C,x]));return{kind:"reuse",state:t,checks:so({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(p){let P=[...p].filter(x=>!N.some(D=>D.id===x));if(P.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${P.join(", ")}`);let C=N.filter(x=>p.has(x.id)&&x.executionCount>=3);if(C.length>0)throw new Error(`Native check retry limit (3) reached: ${C.map(({id:x})=>x).join(", ")}`)}}if(n.execution!==null&&n.checks.length>0){if(!(n.execution.stage==="checking"&&n.execution.actor==="runtime"&&n.checks.some(N=>N.status==="interrupted")&&b)&&!k&&!v)throw new Error("Native check plan was already resolved with a different plan")}else if((n.execution!==null||n.checks.length>0)&&!k&&!v)throw new Error("Native check plan was already resolved with a different plan");let R=gj(),y=await Hr(process.pid),S={...n,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:l,inputFingerprintGate:a,candidateInputFingerprintGate:o,workspace:{...n.workspace,projectRoot:K.resolve(e.projectRoot),worktreeRoot:K.resolve(e.projectRoot),branch:Ke(e.projectRoot),machineId:oo.hostname()},execution:{operationId:R,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...y?{ownerIdentity:y}:{}},checks:e.plans.map(E=>{let N=n.checks.find(P=>P.id===E.id);return v&&N?uv(E,R,e.projectRoot):k&&N?Nj(N,E,R,e.projectRoot):N?.status==="interrupted"&&(p===null||p.has(N.id))?yj(N,E,R,e.projectRoot):N?{...N,operationId:R,activeProcess:null}:uv(E,R,e.projectRoot)})};return await le(i,S,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:S,plans:e.plans.filter(E=>{let N=n.checks.find(P=>P.id===E.id);return k||v||N===void 0||N.status==="interrupted"&&(p===null||p.has(N.id))})}})}async function nf(e){return A(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await O(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=G(e.paths,t.name),i=await lt(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 le(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function cf(e){let t=e.projectRoot??e.paths.projectRoot;Wr(t,e.plans);let r=[],i=new Set;for(let c of e.plans){Cd(t,c);let l=Bc(c);i.has(l)||(i.add(l),r.push(c))}let n=await UG({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=je(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await nf({paths:e.paths,state:n.state,operationId:a,update:f=>({...f,checks:f.checks.map(p=>p.id===c.id?{...p,status:"running",executionCount:p.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:p)})});let u=await cs({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:f})=>{let p=await Hr(f);await nf({paths:e.paths,state:n.state,operationId:a,update:h=>({...h,checks:h.checks.map(m=>m.id===c.id?{...m,activeProcess:{status:"running",pid:f,...p?{identity:p}:{}}}:m)})})}}),d=await hn.readFile(K.resolve(o,...u.logRef.split("/")),"utf8");await nf({paths:e.paths,state:n.state,operationId:a,update:f=>({...f,checks:f.checks.map(p=>{if(p.id!==c.id)return p;let h={...p,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...h,evidenceDigest:Yb(h,d)}})})})}await nf({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await nf({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",activeProcess:null}:u)})})}catch{}throw c}let s=await lt(G(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:so({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function Xb(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await O(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await lt(G(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:dv(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return cf({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function _j(e){let t=G(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>=Tb)throw new Error(`Native Verifier request-checks exceeded ${Tb} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let h=lv(p,e.projectRoot);n.set(h,p),p.status!=="interrupted"&&i.set(h,p),a.set(p.id,h)}let o=new Map,s=new Map;for(let p of e.response.checks){let h=GG(p);Cd(e.projectRoot,h);let m=Bc(h),v=s.get(h.id);if(v!==void 0&&v!==m)throw new Error(`Native Verifier check ID ${h.id} refers to conflicting commands`);let g=a.get(h.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${h.id} conflicts with a Runtime check`);s.set(h.id,m);let w=n.get(m);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);if(w?.status==="interrupted"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(m)||o.set(m,h)}Wr(e.projectRoot,[...o.values()]);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 h=lv(p,e.projectRoot),m=o.get(h);return m&&p.status==="interrupted"?yj(p,m,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>uv(p,r.execution.operationId,e.projectRoot))]};return await le(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 af(e){return A(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await O(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=G(e.paths,t.name),i=await lt(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 le(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Aj(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await af({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=je(e.paths,e.reservation.state.name),a=await cs({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await Hr(s);await af({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await hn.readFile(await T(n,K.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await af({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:Yb(l,o)}})})})}t=await af({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await af({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",activeProcess:null}:n)})})}catch{}throw r}return{checks:so({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)}}}import{randomUUID as YG}from"node:crypto";import fv from"node:path";Fe();gd();as();function Ij(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 XG(e){let{state:t,local:r,envelope:i}=e;if(!xm(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 QG(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Qb(e){return A(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(await vr({paths:e.paths,state:t}),await It({changeDir:X(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Vr(t)})||t.children_contract_hash){let a=await nt({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=JI({state:t,input:e.input}),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Zb(e){return A(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await vr({paths:e.paths,state:t});let i=(await ym({file:G(e.paths,t.name),portableState:t,projectRoot:r,branch:Ke(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");so({local:i,projectRoot:r,supplied:e.checks});let n=GI(t),a=await Be({paths:e.paths,previous:t,next:n}),o=G(e.paths,t.name),s=YG();return await le(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 ek(e){return A(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=G(e.paths,e.name),i=await lt(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await le(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function tk(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await A(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await O(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await vr({paths:e.paths,state:r});let n=await co({paths:e.paths,state:r}),a=XG({state:r,local:n,envelope:e.envelope}),o;try{o=vd(a.payload)}catch(d){let f=`Native Verifier response was invalid: ${d.message}`,p=await sf({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${Qd} was recorded`,{cause:d})}let s=QG(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=so({local:n,projectRoot:i,supplied:e.checks}));let d=KI({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 _j({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 sf({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${Qd} was recorded`,{cause:d})}let u=await Be({paths:e.paths,previous:r,next:l.state});return await le(G(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?bs({local:n,state:u,projectRoot:i}):Te({portableState:u,projectRoot:i,branch:Ke(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await Li({file:fv.join(X(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 Aj({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 A(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await O(e.paths,e.name);return a.state_version!==t.state.state_version?null:sf({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Qd} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function rk(e){return A(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await O(e.paths,e.name),r=await co({paths:e.paths,state:t});if(Ij({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 sf({paths:e.paths,state:t,summary:e.summary})})}async function ik(e){return A(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name);await vr({paths:e.paths,state:t});let r=await co({paths:e.paths,state:t}),i=Ij({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=so({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=YI({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Be({paths:e.paths,previous:t,next:a});return await le(G(e.paths,t.name),bs({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Li({file:fv.join(X(e.paths,t.name),"verification.md"),state:o}),o})}async function nk(e){return A(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await vr({paths:e.paths,state:t});let r=XI({state:t,summary:e.summary}),i=await Be({paths:e.paths,previous:t,next:r});return await le(G(e.paths,t.name),Te({portableState:i,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Li({file:fv.join(X(e.paths,t.name),"verification.md"),state:i}),i})}async function ak(e){return A(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await vr({paths:e.paths,state:t});let r=await co({paths:e.paths,state:t}),i=QI(t,{reason:e.reason}),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),bs({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function ok(e){return A(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await co({paths:e.paths,state:t}),i=ZI(t),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),bs({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function ea(e){return A(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await O(e.paths,e.name);if(mi({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks?await co({paths:e.paths,state:t}):null,i=Yn({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),e.preserveLocalChecks?bs({local:r,state:n,projectRoot:e.paths.projectRoot}):Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function lf(e){if(e.state.verification===null)return"not-applicable";let t=fv.join(X(e.paths,e.state.name),"verification.md");return await Zd({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Li({file:t,state:e.state}),"rebuilt")}import ZG from"node:path";ln();Fe();async function sk(e){return A(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"accept-result"}),await vr({paths:e.paths,state:t});let r=await J(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(ws(r).stateVersion!==r.stateVersion)return Qn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await oe(e.paths,ys(r,t))}let i=UI(t),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Li({file:ZG.join(X(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as jj}from"node:fs";ln();Fe();Xo();async function fl(e){let t=await O(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 nt({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 can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function ck(e){let t=await BI({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 fl({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function pv(e){let t=await O(e.paths,e.name),r=await Oa(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 J(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 jj.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=ws(n);if(i||a.stateVersion!==n.stateVersion){let o=await Qn({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 jj.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await oe(e.paths,ys(n,t)),{state:t,action:"recorded-final-verification"}}async function hv(e){return A(e.paths,`recover Supervisor final verification ${e.name}`,()=>pv(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}sr();Xo();Z();ot();Fe();var Moe=16*1024;async function uf(e){let t=await cm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Tn(t.selection.change),t.selection)}function df(e){return Pc(e.projectRoot)}async function mv(e,t){return A(e,`select change ${t}`,async()=>{Tn(t),await Ae(e,t)?await O(e,t):await Me(e,t),await EN(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Tj(e){let t=await uf(e);return t?(await Ae(e,t.change)?await O(e,t.change):await Me(e,t.change),t.change):null}async function ff(e,t){return await nc(e.projectRoot),PN(e.projectRoot,"native",t)}var hf=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]}},pl=class extends Error{state;constructor(t){super("Native canonical Spec changed independently; the merged delta requires fresh verification"),this.name="NativePortableArchiveRequiresReverificationError",this.state=t}};function lk(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function uk(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=Nt.join(e.archiveDir,t);if(!q(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function pf(e){try{return await ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function $j(e,t){let r=Nt.normalize(Nt.resolve(e)),i=Nt.normalize(Nt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Oj(e,t){let r;try{r=await ze.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=Nt.join(e.archiveDir,n.name);try{let o=await qt(Nt.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 fk(e,t){let r=await Oa(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Dj(e,t){if(t.status!=="prepared"&&t.status!=="specs-applied")return!1;for(let[r,i]of t.spec_changes.entries()){let n=await lo(e,i.capability);if(i.operation!=="remove"&&(i.expected_target_hash===void 0||i.result_hash===void 0)||i.operation==="remove"&&i.expected_target_hash===void 0)return!0;let a=i.operation==="remove"?null:i.result_hash??(i.content===null?null:rt(i.content));if(r<t.next_spec_index){if(n.hash!==a)return!0;continue}if(n.hash!==a&&!(i.operation==="remove"&&n.hash===null)&&(i.expected_target_hash===void 0||n.hash!==i.expected_target_hash))return!0}return!1}async function Hj(e,t){return await fk(e,t)!==null||await Oj(e,t)!==null}async function ks(e,t){await ze.mkdir(e.transactionsDir,{recursive:!0}),await ve(tn(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Fj(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=Vt(e.paths.projectRoot);r.some(a=>$j(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await te(a);if(!o)continue;let s=await Se(a,o.native.artifact_root);i.some(c=>$j(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 ze.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 qt(Nt.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 is(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 tK(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 lo(e,t){let r=Nt.join(e.specsDir,t),i=Nt.join(r,"spec.md");if(!q(e.specsDir,i))throw new Error("Native canonical spec path escaped");let n;try{n=await ze.lstat(e.specsDir)}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await ze.lstat(r)}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[o,s]=await Promise.all([ze.realpath(e.specsDir),ze.realpath(r)]);if(!q(o,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let c;try{c=await ze.lstat(i)}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!q(s,await ze.realpath(i)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{let l=await z({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1});return{text:l.text,hash:rt(l.text)}}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}}async function rK(e){let t=Nt.join(e.paths.specsDir,e.change.capability),r=Nt.join(t,"spec.md");if(!q(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let o=await lo(e.paths,e.change.capability);if(e.change.expected_target_hash===void 0){if(o.hash===null)return;throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`)}if(o.hash===null)return;if(o.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let s;try{s=await ze.lstat(e.paths.specsDir)}catch(d){if(d.code==="ENOENT")return;throw d}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let c;try{c=await ze.lstat(t)}catch(d){if(d.code==="ENOENT")return;throw d}if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[l,u]=await Promise.all([ze.realpath(e.paths.specsDir),ze.realpath(t)]);if(!q(l,u))throw new Error("Native canonical capability path escaped");try{let d=await ze.lstat(r);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await ze.unlink(r)}catch(d){if(d.code!=="ENOENT")throw d}await ze.rmdir(t).catch(d=>{if(d.code!=="ENOENT"&&d.code!=="ENOTEMPTY")throw d});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);if(e.change.expected_target_hash===void 0)throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`);let i=await lo(e.paths,e.change.capability),n=e.change.result_hash??rt(e.change.content);if(i.hash===n)return;if(i.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let a=Nt.join(X(e.paths,e.state.name),e.change.source);await Ne(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),await ze.mkdir(t,{recursive:!0}),await Ne(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function pk(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 iK(e,t){let r=X(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){let s=await lo(e,n.capability);i.push({...n,content:null,expected_target_hash:s.hash});continue}let a=await z({root:r,ref:n.source,maxBytes:null,includeHash:!1});if(n.delta_source){let s=await z({root:r,ref:n.delta_source,maxBytes:null,includeHash:!1}),c=Pi(s.text);if(c.capability!==n.capability)throw new Error(`Native delta capability ${c.capability} does not match ${n.capability}`);let l=await lo(e,n.capability),u=yu({currentMarkdown:l.text,delta:c});i.push({...n,content:u.markdown,delta_content:s.text,source_content:a.text,expected_target_hash:l.hash,result_hash:u.result_hash});continue}let o=await lo(e,n.capability);i.push({...n,content:a.text,expected_target_hash:o.hash,result_hash:rt(a.text)})}return i}function nK(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(pk(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function dk(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=Nt.join(e.specsDir,i);if(r.operation==="remove"){if(r.expected_target_hash===void 0&&!await pf(n))continue;let a=await lo(e,r.capability);if(r.expected_target_hash!==void 0&&a.hash===null)continue}else try{if((await z({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 qj(e){let t=[],r=!1,i=[],n=X(e.paths,e.state.name);for(let a of e.state.spec_changes)try{let o=await lo(e.paths,a.capability);if(!a.delta_source){let u=null;if(a.source!==null){let d=await z({root:n,ref:a.source,maxBytes:null,includeHash:!1});u=rt(d.text)}i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:u});continue}let s=await z({root:n,ref:a.delta_source,maxBytes:null,includeHash:!1}),c=Pi(s.text);if(c.capability!==a.capability)throw new Error(`Native delta capability ${c.capability} does not match ${a.capability}`);let l=yu({currentMarkdown:o.text,delta:c});l.rebased&&(r=!0,t.push(`Native canonical Spec changed independently for ${a.capability}; the merged delta requires fresh verification`)),i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:l.result_hash,delta_source:a.delta_source,delta_operations:l.operationResults})}catch(o){t.push(o.message)}return{blockers:t,requiresReverification:r,specPreview:i}}async function hk(e){let t=await O(e.paths,e.name),r=[],i=!1,n;if(t.document_constraints_version===1){let c=await tf({paths:e.paths,state:t});r.push(...c.findings.map(({message:l})=>l))}try{pk(t)}catch(c){r.push(c.message)}let a=await fk(e.paths,e.name);if(a)try{await Dj(e.paths,a)&&(i=!0,r.push("The interrupted Native Archive transaction is missing a safe canonical binding or has drifted; fresh verification is required")),await dk(e.paths,a)}catch(c){r.push(c.message)}if(a===null){try{let l=await Mi({paths:e.paths,state:t});l.drifted&&r.push(l.reason??"Native confirmed requirements changed")}catch(l){r.push(l.message)}let c=await qj({paths:e.paths,state:t});r.push(...c.blockers),i=c.requiresReverification,n=c.specPreview}else n=a.spec_changes.map(c=>({capability:c.capability,operation:c.operation,source:c.source,current_hash:c.expected_target_hash??null,target_hash:c.content===null?null:rt(c.content),...c.delta_source===void 0?{}:{delta_source:c.delta_source},...c.delta_content?{delta_operations:Pi(c.delta_content).operations.map(l=>({id:l.id,operation:l.operation,status:"changed",targetIds:l.operation==="rename"?[l.id,l.to_id]:[l.id]}))}:{}}));let o=t.verification===null?"missing":await Zd({file:Nt.join(X(e.paths,t.name),"verification.md"),stateVersion:t.state_version});o!=="aligned"&&r.push(`verification.md is ${o}`);let s=await Fj({paths:e.paths,state:t});return s.length>0&&r.push(`capabilities are also declared by: ${s.join(", ")}`),{ready:r.length===0,blockers:r,requiresReverification:i,specPreview:n,capabilityPeers:s,archiveDir:uk(e.paths,lk(t)),stateVersion:t.state_version}}async function mf(e){return A(e.paths,`archive portable change ${e.name}`,async()=>{let t=tK(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await fk(e.paths,e.name),i=X(e.paths,e.name),n=await pf(i),a=n?null:await Oj(e.paths,e.name),o;if(n)o=await O(e.paths,e.name);else if(r)o=await qt(Nt.join(uk(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}`);n&&r!==null&&!o.archived&&o.phase==="verify"&&o.verification_result==="pending"&&o.loop.stage==="verify-ready"&&o.state_version>r.start_state_version&&(await ze.rm(tn(e.paths,{kind:"archive",change:e.name}),{force:!0}),r=null);let s=await J(e.paths,e.name);if(n&&!o.archived&&r!==null&&o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&await Dj(e.paths,r)){let f=await ov({paths:e.paths,state:o}),p=await Qn({paths:e.paths,state:f.state,reason:f.rebased?"Native canonical Spec changed independently after Archive preparation; the delta was re-based before fresh verification.":"Native canonical Spec changed after Archive preparation; fresh verification is required before resuming Archive."});throw await ze.rm(tn(e.paths,{kind:"archive",change:e.name}),{force:!0}),new pl(p)}if(n&&!o.archived&&r===null){let f=await Mi({paths:e.paths,state:o});if(f.drifted){let p=f.reason??"Native confirmed requirements changed";throw await Zn({paths:e.paths,state:o,reason:p,keepFailureBudget:!0}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}if(o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&(await qj({paths:e.paths,state:o})).requiresReverification){let h=await ov({paths:e.paths,state:o}),m=await Qn({paths:e.paths,state:h.state,reason:"Native canonical Spec changed independently; the delta was re-based before fresh verification."});throw new pl(m)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await pv({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 J(e.paths,e.name))}let c=uk(e.paths,r?.archive_ref??lk(o)),l=await pf(c);if(r&&nK(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 ff(e.paths,o.name),await ze.rm(je(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)pk(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await Fj({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new hf(f);r={schema:Bh,id:eK(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:lk(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await iK(e.paths,o),created_at:new Date().toISOString()},await ks(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await ks(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 dk(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>Nt.relative(e.paths.projectRoot,Nt.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await nl({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 rK({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await ks(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await ks(e.paths,r)}if(await dk(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await nl({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 en({file:gt(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await ks(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await pf(i)?i:c;if(await Li({file:Nt.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Zd({file:Nt.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 ks(e.paths,r),s&&!d&&(await nl({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await nl({paths:e.paths,state:s,archiveOwnedPaths:u}),await ze.mkdir(e.paths.archiveDir,{recursive:!0}),await pf(c))throw new Error(`Native Archive target already exists: ${c}`);await ze.rename(i,c),r={...r,status:"moved"},await ks(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await ff(e.paths,o.name),await ze.rm(je(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await ze.rm(tn(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}})}uc();Ya();function gr(e,t,r){return e.language==="zh-CN"?r:t}function aK(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});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:gr(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:gr(e,"Reply A or B","回复 A 或 B"),agentInstruction:gr(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 i(gr(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 i(gr(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}: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 a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"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:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,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."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:gr(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:gr(e,"Accept the result","接受结果"),agentInstruction:gr(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。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Mn)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(gr(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(gr(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 oK(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 sK(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:gr(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:gr(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Vj(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ss(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Lj(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function cK(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Mj(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function lK(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function uK(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 uo(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Vj({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ss("summary","--summary"),cK(e.name,e.flag)]}}function Bj(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:gr(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function dK(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function vv(e){return[uo({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),uo({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function fK(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function L(e,t,r={}){let i=lK(t)&&e.coordination_mode===void 0,n=aK(e,i,t),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:[Ss("summary","--summary")],commandAlternatives:[uo({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:[Ss("summary","--summary")],commandAlternatives:[uo({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...vv({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:[Ss("summary","--summary")],commandAlternatives:[uo({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),uo({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:[Ss("summary","--summary")],commandAlternatives:[uo({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...vv({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:[Ss("summary","--summary")],commandAlternatives:vv({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:vv({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},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?Vj({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:uK({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?[Mj("coordination-mode","--coordination-mode",Oh)]:[]],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:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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}],verification_checks:[Lj()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:h})=>h==="verified");if(s){let h=r.supervisorIntegrationRetryIds;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}],...h&&h.length>0?{retry_check_ids:[...h]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:h})=>h==="blocked"||h==="needs-reverify"),l=t.children.some(({status:h})=>h==="needs-reverify"),u=t.children.some(({status:h})=>h==="ready"||h==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(h=>h.status==="blocked"&&(h.builderFailureCount??0)>=Mn)??null,f=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:gr(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[Ss("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}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=Lj();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${gr(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:fK([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):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;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Bj(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>dK(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Bj(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Mj("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...sK(e)],userCommunication:oK(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[uo({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")}}import{randomUUID as pK}from"node:crypto";import{promises as hl}from"node:fs";import Yj from"node:path";Oe();Ht();Fe();eN();Xo();$h();sr();Z();var mk=["evidence.md","repair.md","archive.md","checkpoint.md"],hK="verification.md";async function mK(e){try{return await hl.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vk(e,t){let r=pe(e,t),i=[tn(e,{kind:"migration",change:t}),Lo(e,t),...mk.map(n=>Yj.join(r,n))];return(await Promise.all(i.map(mK))).some(Boolean)}async function vK(e,t){let r=await Oa(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Wj(e,t){await hl.mkdir(e.transactionsDir,{recursive:!0}),await ve(tn(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function zj(e,t,r={}){let i=r.removeVerificationReport===!1?mk:[...mk,hK];await Promise.all([hl.rm(je(e,t),{recursive:!0,force:!0}),hl.rm(Lo(e,t),{recursive:!0,force:!0}),...i.map(n=>hl.rm(Yj.join(pe(e,t),n),{force:!0}))])}async function Jj(e,t){await le(G(e,t.name),Te({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Gj(e,t){try{let r=await Gt(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 Kj(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ie(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 gK(e){let t=pe(e.paths,e.state.name),r=await z({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 z({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return jh({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Uj(e,t){let r=await is(e,t);if(r.status==="runtime-incompatible")throw new Fr(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Bi(e){return A(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await vK(e.paths,e.name),r=await Ae(e.paths,e.name)?await qt(gt(e.paths,e.name)):null;if(!t&&r)return await zj(e.paths,e.name,{removeVerificationReport:!1}),await Jj(e.paths,r),r;let i=null,n=null;for(t||(i=await Uj(e.paths,e.name),n=await Gj(e.paths,e.name),Kj(e.paths,n),t={schema:Mh,id:pK(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Wj(e.paths,t));;){let a=hC(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Uj(e.paths,e.name),n??=await Gj(e.paths,e.name),Kj(e.paths,n),r=pC({state:i,acceptance:await gK({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await pc(gt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await zj(e.paths,e.name):a.action==="commit-transaction"&&(r??=await qt(gt(e.paths,e.name)),await Jj(e.paths,r)),t={...t,status:a.nextStatus},await Wj(e.paths,t)}return await hl.rm(tn(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??qt(gt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Qj}from"node:fs";import Zj from"node:path";Fe();import{promises as gk}from"node:fs";import wK from"node:path";Qe();var yK=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),NK=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),bK=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),kK=new Set(["status","summary"]);function gv(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function wv(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function SK(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Es(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function EK(e,t,r,i){let n=gv(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=wv(n,yK,"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=gv(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=wv(o,NK,"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=gv(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=wv(c,kK,"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=gv(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:h,...m}=f,v=wv(m,bK,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],w=g.covers.length>0?g.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||h!==void 0&&h!==j("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||!SK(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(f.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} 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((f.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function mn(e){let t=ss(e.paths,e.state.name),r;try{let c=await gk.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Es(t,"","Native Supervisor overlay is not a regular file");r=await gk.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Es(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Es(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=wK.join(e.paths.changesDir,e.state.name),a;try{a=await It({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Es(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 J(e.paths,e.state.name)}catch(c){return Es(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Es(t,r,"Native Supervisor overlay disappeared during inspection");let s=EK(i,e.state,a.contract,o);return s?Es(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 Xj(e){let t=await mn({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 gk.rm(t.file,{force:!1})}sr();$a();function wk(e,t){let r=ie(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 RK(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function PK(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:we(t),completed_at:i});return re({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?RK(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 xK(e){try{let t=await lt(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 Rs(e){return A(e.paths,`recover portable change ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(t.status==="done")return await lf({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=wk(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await mn({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 Xj({paths:e.paths,state:t,expected:i}),n=!0);let a=G(e.paths,e.name),o=await xK(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let m=o.local.execution,v=await ul(o.local),g=m.stage==="verifying"&&m.actor==="verifier"&&m.executionId!==null,w=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&m.stage==="checking"&&m.actor==="runtime";if(g||v!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?m.verifierStartedAt===void 0&&m.requestCheckRounds===0?`Native Verifier execution ${m.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${m.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await le(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await lf({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(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=Yn({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await en({file:gt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await Qj.rm(Zj.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=Te({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await le(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,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 m=PK(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 en({file:gt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let p=Te({portableState:t,projectRoot:e.paths.projectRoot,branch:ie(e.paths.projectRoot).currentBranch});await Qj.mkdir(Zj.dirname(G(e.paths,t.name)),{recursive:!0}),await le(a,p,{containedRoot:e.paths.runtimeDir}),await lf({paths:e.paths,state:t});let h=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:p,action:f?"reverify":"resume-stable-boundary",reason:s,message:h??(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.`)}})}Xo();Oe();bh();fr();import{randomUUID as $K}from"node:crypto";import{accessSync as OK,constants as DK,promises as xs}from"node:fs";import Yr from"node:path";ls();bh();var CK=6e4,jt=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function yk(e,t){try{return Qi("gh",t,{cwd:e,timeoutMs:CK}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function Nk(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function bk(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function eT(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ps(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function tT(e,t){let r=Ps(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 Nv(e,t){let r=Ps(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 rT(e,t){let r=Nk(e,t);if(Ps(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:eT(r.number,`${t}.number`),url:tT(r.url,`${t}.url`),baseBranch:Ps(r.baseRefName,`${t}.baseRefName`),headBranch:Ps(r.headRefName,`${t}.headRefName`),headSha:Nv(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function _K(e){let t=Nk(e,"pull request finish provider output.pullRequest");return{number:eT(t.number,"pull request finish provider output.pullRequest.number"),url:tT(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Ps(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Ps(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Nv(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function AK(e){let t=Nk(bk(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=_K(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function kk(e){let t=yk(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=bk(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:rT(r[0],"gh pr list output[0]")}function iT(e){let t=yk(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=rT(bk(t,"gh pr view output"),"gh pr view output"),i=Nv(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new jt("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new jt(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new jt(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new jt(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function yv(e){try{return kk(e)}catch{return null}}function IK(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 jK(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=yk(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=kk(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new jt("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof jt)throw n;let a=yv(e);if(!a)throw new jt(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=iT({...e,pullRequest:t})}catch(n){throw n instanceof jt?n:new jt(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function TK(e){let[t,...r]=e.config.command,i;try{let o=Qi(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${IK(e)}
|
|
320
|
-
`}).trim();i=AK(o)}catch(o){if(o instanceof jt)throw o;let s=yv(e)??e.existingPullRequest;throw new jt(`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!==Nv(e.headSha,"Native Archive head SHA")){let o=yv(e)??e.existingPullRequest;throw new jt("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=iT({...e,pullRequest:n})}catch(o){if(o instanceof jt)throw o;let s=yv(e)??e.existingPullRequest??n;throw new jt(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function nT(e){let t=kk(e);return e.config?TK({...e,existingPullRequest:t,config:e.config}):jK({...e,existingPullRequest:t})}var Cs="comet.native.workspace-finish.v1",oT="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sT=new RegExp(`^${oT}$`,"u"),HK=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function cT(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Cs||typeof t.name!="string"||!sT.test(t.name)||typeof t.transactionId!="string"||!HK.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Yr.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:Cs,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function bv(e,t){if(!sT.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Yr.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function ta(e,t,r={}){let i=bv(e,t);try{let n=await xs.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=cT(JSON.parse(await xs.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function kv(e,t={}){let r;try{r=await xs.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${oT})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await ta(e,a[1],t);o&&i.push(o)}return i}async function Ek(e,t){let r=bv(e,t),i=Yr.join(e.transactionsDir,`workspace-finish-invalid-${t}-${$K()}.json`);try{return await xs.lstat(r),await xs.rename(r,i),i}catch(n){if(n.code==="ENOENT")return null;throw n}}async function _s(e,t){let r=cT(t);await ve(bv(e,r.name),r,{containedRoot:e.transactionsDir})}async function vl(e,t){try{await xs.unlink(bv(e,t))}catch(r){if(r.code!=="ENOENT")throw r}}var ml=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},Vi=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 Rk(e,t){let r=Yr.relative(e,t);return r===""||!Yr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Yr.sep}`)}function fo(e,t){let r=Yr.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||Yr.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function Sk(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function FK(e,t,r,i=[]){let n=[...zc(e.projectRoot)?[".comet/config.yaml"]:[],fo(e.projectRoot,pe(e,t.name)),fo(e.projectRoot,df(e))];r&&n.push(fo(e.projectRoot,r));for(let a of r?t.spec_changes:i)n.push(fo(e.projectRoot,Ja(e,a.capability)));return n}function qK(e,t){let r=Ln(e).filter(i=>!Sk(i,t));if(r.length>0)throw new Vi(r,e)}function LK(e,t){return t.map(r=>Yr.resolve(e,...r.split("/")))}function MK(e){let t=Ln(e).filter(r=>!(r===".comet/config.yaml"&&zc(e)));if(t.length>0)throw new Vi(LK(e,t),e,`Native merge target worktree is not clean: ${e}`)}function lT(e){return e.split("\0").filter(Boolean)}function BK(e,t){return lT(_(e,["ls-files","-z","--",t]))}function VK(e,t){return lT(_(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function aT(e){try{if(_(e,["config","--get","user.name"])&&_(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function WK(e,t){for(let r of Vt(e))if(ie(r).currentBranch===t)return r;return null}function zK(e,t){try{Qi(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function JK(e,t){if(!t)return;let r=t.command[0];try{if(Yr.posix.isAbsolute(r)||Yr.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=Yr.resolve(e,r);if(!Rk(e,n))throw new Error("configured executable escapes the project root");OK(n,DK.X_OK);return}Qi(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 vf(e){let{paths:t,state:r}=e,i=r.workspace,n=ie(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");return aT(t.projectRoot),{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`);aT(t.projectRoot);let a=FK(t,r,e.archiveDir,e.appliedSpecChanges);i.finish!=="keep"&&qK(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:WK(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}`);MK(o)}let s=i.finish==="push"||i.finish==="pull-request"?G_(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(zK("gh",["--version"]),JK(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 GK(e){try{return await xs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function KK(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,diagnosticArgs:null,recoveryArgs:null}}async function UK(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(Rk(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await Id(e.changeRoot),_(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function Pk(e){let t=KK(e.plan),r=null;try{let i=[fo(e.paths.projectRoot,pe(e.paths,e.name)),fo(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(d=>fo(e.paths.projectRoot,Ja(e.paths,d.capability))),fo(e.paths.projectRoot,df(e.paths))],n=e.plan.isolation==="current"||e.plan.finish==="keep",a=Ln(e.plan.changeRoot).filter(d=>!Sk(d,i)&&!(d===".comet/config.yaml"&&zc(e.plan.changeRoot)));if(a.length>0&&!n)throw t.blockedPaths=a,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${a.join(", ")}`);let o=[],s=new Set;for(let d of i){let f=Yr.resolve(e.paths.projectRoot,...d.split("/"));if(BK(e.plan.changeRoot,d).length>0&&o.push(d),await GK(f))for(let h of VK(e.plan.changeRoot,d))s.add(h)}if(o.length>0&&_(e.plan.changeRoot,["add","-u","--",...o]),s.size>0&&_(e.plan.changeRoot,["add","--",...s]),_(e.plan.changeRoot,["diff","--cached","--name-only","-z","--",...i])){let d=[...new Set([...o,...s])];_(e.plan.changeRoot,n?["commit","--only","-m",`chore(native): archive ${e.name}`,"--",...d]:["commit","-m",`chore(native): archive ${e.name}`])}t.commit=_(e.plan.changeRoot,["rev-parse","HEAD"]);let l=Ln(e.plan.changeRoot).filter(d=>Sk(d,i));if(l.length>0)throw new Error(`Native archive commit left change-owned working-tree changes: ${l.join(", ")}`);if(!n&&!zr(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"){_(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=nT({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 d=Rk(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!d?(await Id(e.plan.changeRoot),_(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 u=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(_(u,["switch",e.plan.targetBranch]),r=u),_(u,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=u,t.cleanup=await UK(e.plan),t}catch(i){if(i instanceof jt&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{_(r,["merge","--abort"])}catch{}try{ie(r).currentBranch===e.plan.targetBranch&&_(r,["switch",e.plan.changeBranch]),n=ie(r).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=r)}throw t.status="blocked",t.message=i.message,t.diagnosticArgs=["git","-C",e.plan.finish==="merge"&&t.targetRoot?t.targetRoot:e.plan.changeRoot,"status","--short"],t.recoveryArgs=["comet","native","archive",e.name,"--confirmed"],new ml(t)}}Z();var Ck=Ji(Ri(),1);fr();Qe();Ht();sr();import{promises as YK}from"node:fs";import xk from"node:path";var Sv=class extends Error{};async function gf(e,t){let r=await z({root:e.nativeRoot,ref:xk.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,Ck.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new Sv("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:re(i)}}async function dT(e,t,r){let i;try{i=await YK.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=xk.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await gf(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof Sv)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function Ev(e){return j("comet.native.status-record.v1",e)}function uT(e){let t=xk.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=_(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=re((0,Ck.parse)(_(e.projectRoot,["show",`${r}:${t}`])));return Ev(i)===Ev(e.state)?r:null}catch{return null}}function fT(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=uT(e),i=uT(t);if(!r||!i)return!1;try{return _(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function pT(e,t){return e.state.archived&&t.state.archived&&Ev(e.state)===Ev(t.state)}Cu();import Cf from"path";import{realpathSync as PY}from"fs";function wf(e){return e.charCodeAt(0)===65279?e.slice(1):e}function hT(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var ra={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mT(e){return e?e.command?`${ra.next} ${e.command}`:e.ask_user?`${ra.next} ${e.ask_user}`:null:null}function vT(e,t){let r=[e.summary],i=mT(e.next);return i&&r.push(i),e.user_message&&r.push("",ra.relay,e.user_message),t!==void 0&&r.push("",ra.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
319
|
+
`)}async function tf(e){let t=X(e.paths,e.state.name),r=[...(await pd(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:l})=>l!=="remove"),o=e.state.spec_changes.filter(({operation:l})=>l!=="remove"),s=new Set(a.map(({capability:l})=>l));if(e.specChanges!==void 0)for(let l of o)s.has(l.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${l.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${l.capability}/spec.md`});let c=n.length>0&&n.every(({operation:l})=>l==="remove");a.length===0&&o.length===0&&!c&&!qG(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let l of a){let u=`specs/${l.capability}/spec.md`;if(l.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:l.source??u});continue}try{let d=(await z({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...oA(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function av(e){let t=await tf(e);if(!t.valid)throw new Error(fj(t.findings,{change:e.state.name,phase:e.state.phase}))}function mi(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Mb(e){return A(e.paths,`create portable change ${e.name}`,async()=>{if(!cn.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await te(e.paths.projectRoot)===null&&await Dr(e.paths.projectRoot,e.initialProjectConfig),Z_(e.paths.projectRoot,e.workspaceBinding);let t=(await V_(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new Ic(e.workspaceBinding?.isolation??"current",t);let r=X(e.paths,e.name),i=je(e.paths,e.name);await Promise.all([T(e.paths.nativeRoot,r),T(e.paths.runtimeDir,i)]);let n=!1,a=!1;try{await Ur.mkdir(e.paths.changesDir,{recursive:!0}),await Ur.mkdir(r,{recursive:!1}),n=!0,await Ur.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await Ur.mkdir(i,{recursive:!1}),a=!0,await Ur.mkdir(Ut.join(r,"specs"),{recursive:!0}),await Ne(Ut.join(r,"brief.md"),Nu(e.language));let o=Xy({name:e.name,language:e.language,workspace:Q_(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await pc(gt(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await le(G(e.paths,e.name),Te({portableState:o,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await Ur.rm(i,{recursive:!0,force:!0}),n&&await Ur.rm(r,{recursive:!0,force:!0}),o}})}async function rf(e){let t=X(e.paths,e.state.name),r=Ut.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Ur.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(!cn.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=Ut.join(t,...s.split("/")),l=await Ur.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Ut.join(e.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let v=await Ur.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=rt((await z({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let p=`specs/${o.name}/${Ys}`,h=Ut.join(t,...p.split("/")),m={};try{let v=await Ur.lstat(h);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let g=await z({root:t,ref:p,maxBytes:null,includeHash:!1}),w=Pi(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let k=f??rt(""),b=e.state.spec_changes.find(R=>R.capability===o.name);if(b?.delta_source!==void 0){if(b.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==k)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);m={delta_source:p,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...m})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function ov(e){let t=X(e.paths,e.state.name),r=await rf(e),i=[...r],n=[],a=[];for(let[s,c]of r.entries()){if(!c.delta_source||!c.source)continue;let l=await z({root:t,ref:c.delta_source,maxBytes:null,includeHash:!1}),u=Pi(l.text),d="";try{d=(await z({root:e.paths.specsDir,ref:`${c.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(w){if(w.code!=="ENOENT")throw w}let f=yu({currentMarkdown:d,delta:u});if(!f.rebased)continue;let p=th(d),h=Object.fromEntries(p.requirements.map(w=>[w.id,rt(w.raw)])),m=u.independent_requirements===void 0?void 0:Object.fromEntries(Object.keys(u.independent_requirements).flatMap(w=>{let k=p.requirements.find(b=>b.id===w);return k?[[w,rt(k.raw)]]:[]})),v={...u,base_hash:rt(d),base_version:u.base_version+1,legacy_hash:jo(d),base_requirements:h,...m===void 0?{}:{independent_requirements:m}},g=await z({root:t,ref:c.source,maxBytes:null,includeHash:!1});a.push({index:s,spec:c,originalDeltaText:l.text,originalSourceText:g.text,deltaText:eh(v),sourceText:f.markdown}),i[s]={...c,base_hash:v.base_hash},n.push(c.capability)}if(n.length===0)return{state:e.state,rebased:!1,capabilities:n};let o=!1;try{for(let d of a)await Ne(Ut.join(t,...d.spec.delta_source.split("/")),d.deltaText,{containedRoot:e.paths.nativeRoot}),await Ne(Ut.join(t,...d.spec.source.split("/")),d.sourceText,{containedRoot:e.paths.nativeRoot});let s={...e.state,spec_changes:i},c=await ol({paths:e.paths,state:s,specChanges:i});if(!Th(e.state.acceptance,c.acceptance))throw new Error("Native delta rebase changed the confirmed acceptance scope; explicit Shape confirmation is required");let l=await It({changeDir:t,acceptanceIds:c.acceptance.map(({id:d})=>d),validation:Vr({...s,acceptance:c.acceptance})}),u=await Be({paths:e.paths,previous:e.state,next:{...e.state,state_version:e.state.state_version+1,spec_changes:i,shape_confirmation_hash:sl({formalHash:c.formalHash,childrenHash:l?.hash??null,coordinationMode:e.state.coordination_mode})}});return o=!0,{state:u,rebased:!0,capabilities:n}}catch(s){if(!o)for(let c of a)await Ne(Ut.join(t,...c.spec.delta_source.split("/")),c.originalDeltaText,{containedRoot:e.paths.nativeRoot}),await Ne(Ut.join(t,...c.spec.source.split("/")),c.originalSourceText,{containedRoot:e.paths.nativeRoot});throw s}}async function ol(e){let t=X(e.paths,e.state.name),r=await z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(LN(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await z({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await z({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=Pi(u.text);c=ox(s.text,d);let f="";try{f=(await z({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(rt(f)===d.base_hash){let p=py({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(rt(s.text)!==p.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=j("comet.native.shape-artifact-content.v1",nv(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:j("comet.native.shape-artifact-content.v1",nv(s.text)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await z({root:t,ref:Lb,maxBytes:65536,includeHash:!1}),s=lj(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=Ut.relative(e.paths.projectRoot,Ut.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(Ut.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=j("comet.native.shape-artifact-content.v1",nv(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:jh({briefMarkdown:r.text,specs:i}),formalHash:j("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:j("comet.native.shape-artifact-content.v1",nv(r.text))},specs:n,association:{source:Lb,contentHash:a}})}}function sl(e){return j("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Bb(e){return A(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(mi({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 rf({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await av({paths:e.paths,state:t,specChanges:r});let i=await ol({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await It({changeDir:X(e.paths,t.name),acceptanceIds:n.map(({id:f})=>f),validation:Vr({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await $m(e.paths,t.name);let f=bm(t.workspace,e.paths.projectRoot);if(f===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=pt({...t,workspace:f},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:we(`Native workspace bound to branch ${f.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await Xd(X(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let c=s?e.coordinationMode??t.coordination_mode:void 0;if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let l={...o,spec_changes:r,shape_confirmation_hash:sl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})};delete l.children_contract_hash,delete l.coordination_mode,s&&(l.coordination_mode=c);let u=zI({state:l,acceptance:n.map(f=>({...f}))});e.enforceDocumentConstraints===!0&&(u.document_constraints_version=1),a&&(u.children_contract_hash=al({acceptance:u.acceptance,children:a.contract}));let d=await Be({paths:e.paths,previous:t,next:u});return await le(G(e.paths,t.name),Te({portableState:d,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),d})}async function Mi(e){if(e.state.document_constraints_version===1){let l=await tf(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await rf(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.delta_source===d.delta_source&&l.base_hash===d.base_hash&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await ol({...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(!Th(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await It({changeDir:X(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Vr({...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&&sl({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?al({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 sv(e){return A(e.paths,`recover pending Shape confirmation ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.next_action!=="confirm-shape")return{state:t,repaired:!1,reason:null};let r=await Mi({paths:e.paths,state:t});if(!r.drifted)return{state:t,repaired:!1,reason:null};let i=r.reason??"Native confirmed requirements changed";return{state:await Zn({paths:e.paths,state:t,reason:i,keepFailureBudget:!0}),repaired:!0,reason:i}})}async function vr(e){let t=await Mi(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Zn({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Vb(e){return A(e.paths,`sync spec references ${e.name}`,async()=>{let t=await O(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(!cn.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await vr({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:h,operation:m})=>h===e.capability&&m!=="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(h=>!t.acceptance.some(m=>m.id===h))||t.acceptance.some(({source:h,id:m})=>h===r.source&&!i.has(m)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:h,to:m})=>!/^[A-Za-z0-9_./#%-]+$/u.test(h)||!/^[A-Za-z0-9_./#%-]+$/u.test(m)||h===m)||new Set(e.replacements.map(({from:h})=>h)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=X(e.paths,t.name),a=await z({root:n,ref:r.source,maxBytes:null,includeHash:!1}),o=new Map(e.replacements.map(({from:h,to:m})=>[h,m])),s=new Set,c=null,l=!1,u=a.text.split(/(?<=\n)/u).map(h=>{let m=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(h.trimEnd());return m?(c?m[1][0]===c.marker&&m[1].length>=c.length&&!m[2].trim()&&(c=null):c={marker:m[1][0],length:m[1].length},h):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(h)?h:(h.includes("<!--")&&(l=!0),l?(h.includes("-->")&&(l=!1),h):c||/^(?: {4}|\t)/u.test(h)||h.includes("`")?h:h.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(v,g,w)=>{let k=o.get(w);return k?(s.add(w),`[${g}](${k})`):v}))}).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=Ut.join(n,r.source);await Ne(d,u,{containedRoot:e.paths.nativeRoot});let f=!1,p=null;try{let h=await ol({paths:e.paths,state:t,specChanges:t.spec_changes});if(!Th(t.acceptance,h.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let m=y=>DG("sha256").update(y).digest("hex"),v=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:m(a.text),afterHash:m(u),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=m(v),w=await tl({paths:e.paths,name:t.name,hash:g,text:v,onCreated:()=>{p=g}}),k={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},b=t.phase==="build"?{...k,state_version:t.state_version+1,acceptance:t.acceptance.map(y=>i.has(y.id)?{...y,result:"pending",reason:null}:y)}:Yn({state:k,reason:`Spec reference sync: ${e.reason}`});b=pt(b,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:we(`Spec reference sync by ${e.actor}: ${e.reason}; ${w}`),completed_at:new Date().toISOString()}),b.shape_confirmation_hash=sl({formalHash:h.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let R=await Be({paths:e.paths,previous:t,next:b});return f=!0,await le(G(e.paths,t.name),Te({portableState:R,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),R}catch(h){if(!f)try{(await O(e.paths,t.name)).state_version===t.state_version&&(await Ne(d,a.text,{containedRoot:e.paths.nativeRoot}),p&&await gb({paths:e.paths,name:t.name,hash:p}))}catch{}throw h}})}async function Wb(e){if(!cn.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return A(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await O(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 Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function zb(e){return A(e.paths,`disassociate portable capability ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(mi({state:t,expected:e.expectedContinuation,action:"disassociate-capability"}),t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=Ut.join(X(e.paths,e.name),Lb),i;try{i=await Ur.lstat(r)}catch(n){if(n.code==="ENOENT")return t;throw n}if(!i.isFile()||i.isSymbolicLink())throw new Error("Native capability association must be a regular file");return await Ur.rm(r),Zn({paths:e.paths,state:t,reason:"Capability association revoked through comet native spec disassociate"})})}async function cv(e){return A(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await O(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 Be({paths:e.paths,previous:t,next:r});return await le(G(e.paths,t.name),Te({portableState:i,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await Li({file:Ut.join(X(e.paths,t.name),"verification.md"),state:i}),i})}async function Ns(e){return A(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await O(e.paths,e.name);if(mi({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:Zn({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function Zn(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:we(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:e.keepFailureBudget?t.loop.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 Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}ot();Fe();Ya();ln();sr();$a();async function Jb(e){return A(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(mi({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 vr({paths:e.paths,state:t});let r=await rf({paths:e.paths,state:t}),i=await ol({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await It({changeDir:X(e.paths,t.name),acceptanceIds:n.map(({id:g})=>g),validation:Vr({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await $m(e.paths,t.name);let g=bm(t.workspace,e.paths.projectRoot);if(g===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=pt({...t,workspace:g},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:we(`Native workspace bound to branch ${g.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await Xd(X(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=t.coordination_mode;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=sl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let g=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Zn({paths:e.paths,state:t,reason:g,keepFailureBudget:!0}),new Error(`${g}; Native change returned to Shape and requires confirmation`)}let u=WI({state:{...o,spec_changes:r},acceptance:n.map(g=>({...g}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=al({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let g=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(g?.outcome==="fail"&&g.unresolved_ids.length>0){let w=await nt({paths:e.paths,state:u}),k=new Map((w?.children??[]).map(({name:y,status:S})=>[y,S])),b=new Set(a.contract.children.filter(({name:y})=>{let S=k.get(y);return S!=="done"&&S!=="integrated"&&S!=="archived"}).flatMap(({covers:y})=>y)),R=g.unresolved_ids.filter(y=>!b.has(y));if(R.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${R.join(", ")}`)}}let d=null,f=a?.contract.schema==="comet.native.children.v2"?await J(e.paths,t.name):null,p=null,h=null;if(a?.contract.schema==="comet.native.children.v2"){if(p=o.workspace.change_branch??o.workspace.target_branch,!p)throw new Error("Native Supervisor v2 requires a target branch");if(h=er(e.paths.projectRoot,p),!h)throw new Error(`Native Supervisor target branch has no commit: ${p}`);f||(f=await Yd({paths:e.paths,parent:t.name,targetBranch:p,contract:a.contract})),f||(d=await Cb({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:p,sourceConfig:await te(e.paths.projectRoot)}))}let m=a?.contract.schema==="comet.native.children.v2"&&p&&h?f?GN({state:f,contract:a.contract}):d?Nd({parent:u.name,targetBranch:p,targetCommit:h,integrationBranch:d.binding.changeBranch,integrationWorktree:d.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!m)throw new Error("Native Supervisor integration state is unavailable");let v=await Be({paths:e.paths,previous:t,next:u});return await le(G(e.paths,t.name),Te({portableState:v,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),m&&await oe(e.paths,m),v})}fr();$u();Qe();Vc();import{createHash as vj,randomUUID as gj}from"node:crypto";import{promises as hn}from"node:fs";import oo from"node:os";import K from"node:path";Fe();$a();Z();async function Gb(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}function dv(e,t){let r=K.relative(K.resolve(e),K.resolve(t));if(K.isAbsolute(r)||r===".."||r.startsWith(`..${K.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(K.sep).join("/");return Pd(e,i),i}function LG(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function lv(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Bc({id:e.id,name:e.name,executable:r,argv:i,cwdRef:dv(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function dl(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:dv(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function wj(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||K.resolve(e.workspace.projectRoot)!==K.resolve(r)||K.resolve(e.workspace.worktreeRoot)!==K.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==oo.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>lv(o,r)===Bc(t[s]))}function pj(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>lv(i,r)===Bc(t[n]))}async function ul(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await oc(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await oc(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function hj(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function uv(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:Pd(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function yj(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 Nj(e,t,r,i)}function Nj(e,t,r,i){return{...uv(t,r,i),executionCount:e.executionCount}}function bj(e){return vj("sha256").update(e).digest("hex")}async function of(e){let t=await hn.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=vj("sha256"),i=await hn.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(MG);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await hn.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var kj=2e4,Sj=1024*1024*1024,MG=65535,Ej=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],BG=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),Kb=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],Rj=new Set(["comet-state.yaml","children.yaml","verification.md"]);function ll(e,t){if(!t)return[...Kb];let r=K.relative(e,t).replaceAll("\\","/");if(K.isAbsolute(r)||r===".."||r.startsWith("../"))return[...Kb];let i=r===""?"":`${r}/`;return[...Kb,...["changes","archive"].flatMap(n=>[...Rj].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function Ub(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!Rj.has(K.basename(i)))return!1;let n=K.resolve(t,...i.split("/")),a=K.relative(K.resolve(r),n);if(K.isAbsolute(a)||a===".."||a.startsWith(`..${K.sep}`))return!1;let[,o]=a.split(K.sep);return a.startsWith(`comet${K.sep}`)&&(o==="changes"||o==="archive")}function cl(){return{complete:!1,files:[]}}function VG(e){let t=e==="."?"":`${e}/`;return Ej.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function Pj(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function xj(e,t,r){let i=[...new Set(t.map(({cwdRef:s})=>s))];if(i.length===0)return{complete:!0,files:[]};let n;try{n=[...new Set(_(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...i.flatMap(VG)]).split("\0").filter(Boolean).map(s=>s.replaceAll("\\","/")))].sort()}catch{return cl()}if(n.length>kj)return cl();let a=[],o=0;for(let s of n){if(Ub(s,e,r))continue;let c=K.resolve(e,...s.split("/"));if(!q(e,c)||Pj(s))return cl();try{let l=await hn.lstat(c);if(!l.isFile()||o+l.size>Sj)return cl();let{digest:u,size:d}=await of(c);o+=d,a.push({path:s,digest:u,size:d})}catch{return cl()}}return{complete:!0,files:a}}async function WG(e,t,r){let i=[...new Set(t.map(({cwdRef:c})=>c))],n=new Map,a=0,o=c=>Ej.includes(c),s=async(c,l,u)=>{let d;try{d=await hn.readdir(c,{withFileTypes:!0})}catch{return!1}d.sort((f,p)=>f.name.localeCompare(p.name,"en"));for(let f of d){let p=l?`${l}/${f.name}`:f.name;if(Ub(p,e,r)||f.isDirectory()&&BG.has(f.name))continue;let h=K.join(c,f.name);if(f.isDirectory()){if(!await s(h,p,u||o(f.name)))return!1;continue}if(u){if(Pj(p)||!f.isFile())return!1;try{let m=await hn.lstat(h);if(a+m.size>Sj)return!1;let{digest:v,size:g}=await of(h);if(a+=g,n.set(p,{path:p,digest:v,size:g}),n.size>kj)return!1}catch{return!1}}}return!0};for(let c of i){let l=Pd(e,c);if(!await s(l,c==="."?"":c,o(K.basename(l))))return cl()}return{complete:!0,files:[...n.values()].sort((c,l)=>c.path.localeCompare(l.path,"en"))}}function Yb(e,t){return j("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:K.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:bj(t)})}async function zG(e){let t={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},r=!1;try{t.head=_(e.projectRoot,["rev-parse","HEAD"]),r=!0,t.branch=_(e.projectRoot,["branch","--show-current"]),t.status=_(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...ll(e.projectRoot,e.managedArtifactRoot)]);let i=_(e.projectRoot,["diff","--name-only","-z","HEAD","--",...ll(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.diff=await Gb(i,4,async o=>{let s=K.resolve(e.projectRoot,...o.split("/"));try{let{digest:c}=await of(s);return{path:o,digest:c}}catch{return{path:o,digest:null}}}),t.diff.some(({digest:o})=>o===null)&&(t.complete=!1);let n=_(e.projectRoot,["ls-files","--stage","-z","--",...ll(e.projectRoot,e.managedArtifactRoot)]);t.stagedDiff=bj(n),t.submodules=LG(n)?_(e.projectRoot,["submodule","status","--recursive"]):"";let a=_(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...ll(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.untracked=await Gb(a,4,async o=>{let s=K.resolve(e.projectRoot,...o.split("/"));try{let{digest:c,size:l}=await of(s);return{path:o,digest:c,size:l}}catch{return{path:o,digest:null,size:null}}}),t.untracked.some(({digest:o})=>o===null)&&(t.complete=!1),t.ignored=await xj(e.projectRoot,e.plans,e.managedArtifactRoot),t.ignored.complete||(t.complete=!1)}catch{r?t.complete=!1:(t.capture="physical-tree",t.physical=await WG(e.projectRoot,e.plans,e.managedArtifactRoot),t.complete=t.physical.complete)}return j("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:i,source:n,text:a})=>({id:i,source:n,text:a})),git:t,projectRoot:K.resolve(e.projectRoot),machineId:oo.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([i])=>Cj.has(i.toUpperCase())).map(([i,n])=>[i,n??null]).sort(([i],[n])=>i.localeCompare(n))})}var Cj=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function JG(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function GG(){return Object.entries(process.env).filter(([e])=>Cj.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function mj(e){try{let t=_(e.projectRoot,["rev-parse","HEAD"]),r=_(e.projectRoot,["branch","--show-current"]),i=_(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...ll(e.projectRoot,e.managedArtifactRoot)]),n=_(e.projectRoot,["ls-files","--stage","-z","--",...ll(e.projectRoot,e.managedArtifactRoot)]);if(t===null||i===null)return null;let a=[];for(let s of Ln(e.projectRoot).filter(c=>!Ub(c,e.projectRoot,e.managedArtifactRoot))){let c=K.resolve(e.projectRoot,...s.split("/")),l=null;try{l=(await of(c)).digest}catch{return null}a.push({path:s,digest:l})}a.sort((s,c)=>s.path.localeCompare(c.path,"en"));let o=await xj(e.projectRoot,e.plans??[],e.managedArtifactRoot);return o.complete?j("comet.native.check-input-gate.v1",{candidateId:e.candidateId,head:t,branch:r,status:i,staged:n,workingTree:a,ignored:o,projectRoot:K.resolve(e.projectRoot),machineId:oo.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:GG()}):null}catch{return null}}function so(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`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:we(i),argv_display:xd(r.argv.slice(1)).map(n=>we(n)),argv_truncated:!1,cwd_ref:dv(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:JG(r)}})}function KG(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function bs(e){if(e.local===null||e.local.change!==e.state.name)return Te({portableState:e.state,projectRoot:e.projectRoot,branch:Ke(e.projectRoot)});let t=e.local.execution?.operationId??gj();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 co(e){try{let t=await lt(G(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function sf(e){let t=await co({paths:e.paths,state:e.state}),r=Xm({state:e.state,summary:e.summary}),i=await Be({paths:e.paths,previous:e.state,next:r});return await le(G(e.paths,e.state.name),bs({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function UG(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await T(t,K.resolve(t,...r.log.split(/[\\/]/u)));if(!(await hn.stat(i)).isFile())return!1;let n=await hn.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==Yb(r,n))return!1}catch{return!1}}return!0}async function YG(e){return A(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(await vr({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=Ke(e.projectRoot),i=G(e.paths,t.name),n=(await ym({file:i,portableState:t,projectRoot:e.projectRoot,branch:r,containedRoot:e.paths.runtimeDir})).state,a=await mj({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),o=await mj({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:[],managedArtifactRoot:e.paths.artifactRoot}),s=a===null,l=a!==null&&n.inputFingerprint!==null&&n.inputFingerprintGate===a&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.machineId===oo.hostname()?n.inputFingerprint:await zG({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),u=je(e.paths,t.name),d=await UG(n,u),f=n.checks.every(E=>E.status==="passed"),p=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),h=n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===oo.hostname()&&n.inputFingerprint===l,m=o!==null&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===oo.hostname(),v=m&&n.inputFingerprint!==null&&n.inputFingerprint!==l,g=wj(n,e.plans,e.projectRoot,t,l,r)||m&&pj(n,e.plans,e.projectRoot),w=n.candidateId===t.builder_handoff?.candidate_id&&K.resolve(n.workspace.projectRoot)===K.resolve(e.projectRoot)&&K.resolve(n.workspace.worktreeRoot)===K.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===oo.hostname(),k=h&&f&&!d;if(p&&p.size===0)throw new Error("Native check retry list must contain at least one ID");if(!h&&n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&n.execution.status==="running"){let E=await ul(n);if(E!=="orphaned")throw new Error(E==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");n=hj(n),await le(i,n,{containedRoot:e.paths.runtimeDir})}if(!h&&w&&n.inputFingerprint!==null&&(n.execution!==null||n.checks.length>0)){let E=n.inputFingerprint!==l;if(!(s&&!E||v)){let N=Yn({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),P=await Be({paths:e.paths,previous:t,next:N});throw await le(i,Te({portableState:P,projectRoot:e.paths.projectRoot,branch:r}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!h&&!m){let E=Te({portableState:t,projectRoot:e.projectRoot,branch:r});await le(i,E,{containedRoot:e.paths.runtimeDir}),n=E}let b=pj(n,e.plans,e.projectRoot);if(n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&b&&g){let E=n.execution;if(E.status==="running"){let P=await ul(n);if(P!=="orphaned")throw new Error(P==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");n=hj(n),await le(i,n,{containedRoot:e.paths.runtimeDir}),E=n.execution}let N=n.checks.filter(P=>P.status==="interrupted");if(N.length===0&&E.status==="completed"&&f&&!k&&!v){let P=new Map(e.plans.map(({id:C,name:x})=>[C,x]));return{kind:"reuse",state:t,checks:so({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(N.length===0&&E.status==="completed"&&!f&&!k&&!v)throw new Error(`Native check plan contains a failed check (${n.checks.filter(({status:P})=>P==="failed").map(({id:P})=>P).join(", ")}); submit a new Builder candidate`);if(N.length>0&&N.some(P=>!P.repeatable)&&!k){let P=Yn({state:t,reason:`A non-repeatable Runtime check was interrupted (${N.filter(x=>!x.repeatable).map(({id:x})=>x).join(", ")}); a new Builder candidate is required before it can run again.`}),C=await Be({paths:e.paths,previous:t,next:P});throw await le(G(e.paths,t.name),Te({portableState:C,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${N.find(x=>!x.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(N.length>0&&p===null&&!k&&!v){let P=new Map(e.plans.map(({id:C,name:x})=>[C,x]));return{kind:"reuse",state:t,checks:so({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(p){let P=[...p].filter(x=>!N.some(D=>D.id===x));if(P.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${P.join(", ")}`);let C=N.filter(x=>p.has(x.id)&&x.executionCount>=3);if(C.length>0)throw new Error(`Native check retry limit (3) reached: ${C.map(({id:x})=>x).join(", ")}`)}}if(n.execution!==null&&n.checks.length>0){if(!(n.execution.stage==="checking"&&n.execution.actor==="runtime"&&n.checks.some(N=>N.status==="interrupted")&&b)&&!k&&!v)throw new Error("Native check plan was already resolved with a different plan")}else if((n.execution!==null||n.checks.length>0)&&!k&&!v)throw new Error("Native check plan was already resolved with a different plan");let R=gj(),y=await Hr(process.pid),S={...n,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:l,inputFingerprintGate:a,candidateInputFingerprintGate:o,workspace:{...n.workspace,projectRoot:K.resolve(e.projectRoot),worktreeRoot:K.resolve(e.projectRoot),branch:Ke(e.projectRoot),machineId:oo.hostname()},execution:{operationId:R,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...y?{ownerIdentity:y}:{}},checks:e.plans.map(E=>{let N=n.checks.find(P=>P.id===E.id);return v&&N?uv(E,R,e.projectRoot):k&&N?Nj(N,E,R,e.projectRoot):N?.status==="interrupted"&&(p===null||p.has(N.id))?yj(N,E,R,e.projectRoot):N?{...N,operationId:R,activeProcess:null}:uv(E,R,e.projectRoot)})};return await le(i,S,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:S,plans:e.plans.filter(E=>{let N=n.checks.find(P=>P.id===E.id);return k||v||N===void 0||N.status==="interrupted"&&(p===null||p.has(N.id))})}})}async function nf(e){return A(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await O(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=G(e.paths,t.name),i=await lt(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 le(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function cf(e){let t=e.projectRoot??e.paths.projectRoot;Wr(t,e.plans);let r=[],i=new Set;for(let c of e.plans){Cd(t,c);let l=Bc(c);i.has(l)||(i.add(l),r.push(c))}let n=await YG({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=je(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await nf({paths:e.paths,state:n.state,operationId:a,update:f=>({...f,checks:f.checks.map(p=>p.id===c.id?{...p,status:"running",executionCount:p.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:p)})});let u=await cs({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:f})=>{let p=await Hr(f);await nf({paths:e.paths,state:n.state,operationId:a,update:h=>({...h,checks:h.checks.map(m=>m.id===c.id?{...m,activeProcess:{status:"running",pid:f,...p?{identity:p}:{}}}:m)})})}}),d=await hn.readFile(K.resolve(o,...u.logRef.split("/")),"utf8");await nf({paths:e.paths,state:n.state,operationId:a,update:f=>({...f,checks:f.checks.map(p=>{if(p.id!==c.id)return p;let h={...p,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...h,evidenceDigest:Yb(h,d)}})})})}await nf({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await nf({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",activeProcess:null}:u)})})}catch{}throw c}let s=await lt(G(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:so({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function Xb(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await O(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await lt(G(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:dv(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return cf({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function _j(e){let t=G(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>=Tb)throw new Error(`Native Verifier request-checks exceeded ${Tb} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let h=lv(p,e.projectRoot);n.set(h,p),p.status!=="interrupted"&&i.set(h,p),a.set(p.id,h)}let o=new Map,s=new Map;for(let p of e.response.checks){let h=KG(p);Cd(e.projectRoot,h);let m=Bc(h),v=s.get(h.id);if(v!==void 0&&v!==m)throw new Error(`Native Verifier check ID ${h.id} refers to conflicting commands`);let g=a.get(h.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${h.id} conflicts with a Runtime check`);s.set(h.id,m);let w=n.get(m);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);if(w?.status==="interrupted"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(m)||o.set(m,h)}Wr(e.projectRoot,[...o.values()]);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 h=lv(p,e.projectRoot),m=o.get(h);return m&&p.status==="interrupted"?yj(p,m,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>uv(p,r.execution.operationId,e.projectRoot))]};return await le(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 af(e){return A(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await O(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=G(e.paths,t.name),i=await lt(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 le(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Aj(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await af({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=je(e.paths,e.reservation.state.name),a=await cs({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await Hr(s);await af({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await hn.readFile(await T(n,K.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await af({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:Yb(l,o)}})})})}t=await af({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await af({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",activeProcess:null}:n)})})}catch{}throw r}return{checks:so({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)}}}import{randomUUID as XG}from"node:crypto";import fv from"node:path";Fe();gd();as();function Ij(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 QG(e){let{state:t,local:r,envelope:i}=e;if(!xm(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 ZG(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Qb(e){return A(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(await vr({paths:e.paths,state:t}),await It({changeDir:X(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Vr(t)})||t.children_contract_hash){let a=await nt({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=JI({state:t,input:e.input}),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Zb(e){return A(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await vr({paths:e.paths,state:t});let i=(await ym({file:G(e.paths,t.name),portableState:t,projectRoot:r,branch:Ke(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");so({local:i,projectRoot:r,supplied:e.checks});let n=GI(t),a=await Be({paths:e.paths,previous:t,next:n}),o=G(e.paths,t.name),s=XG();return await le(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 ek(e){return A(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=G(e.paths,e.name),i=await lt(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await le(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function tk(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await A(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await O(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await vr({paths:e.paths,state:r});let n=await co({paths:e.paths,state:r}),a=QG({state:r,local:n,envelope:e.envelope}),o;try{o=vd(a.payload)}catch(d){let f=`Native Verifier response was invalid: ${d.message}`,p=await sf({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${Qd} was recorded`,{cause:d})}let s=ZG(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=so({local:n,projectRoot:i,supplied:e.checks}));let d=KI({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 _j({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 sf({paths:e.paths,state:r,summary:f});throw new Error(`${f}; execution error ${p.loop.execution_failure_count}/${Qd} was recorded`,{cause:d})}let u=await Be({paths:e.paths,previous:r,next:l.state});return await le(G(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?bs({local:n,state:u,projectRoot:i}):Te({portableState:u,projectRoot:i,branch:Ke(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await Li({file:fv.join(X(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 Aj({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 A(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await O(e.paths,e.name);return a.state_version!==t.state.state_version?null:sf({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Qd} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function rk(e){return A(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await O(e.paths,e.name),r=await co({paths:e.paths,state:t});if(Ij({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 sf({paths:e.paths,state:t,summary:e.summary})})}async function ik(e){return A(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name);await vr({paths:e.paths,state:t});let r=await co({paths:e.paths,state:t}),i=Ij({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=so({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=YI({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Be({paths:e.paths,previous:t,next:a});return await le(G(e.paths,t.name),bs({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Li({file:fv.join(X(e.paths,t.name),"verification.md"),state:o}),o})}async function nk(e){return A(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await vr({paths:e.paths,state:t});let r=XI({state:t,summary:e.summary}),i=await Be({paths:e.paths,previous:t,next:r});return await le(G(e.paths,t.name),Te({portableState:i,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Li({file:fv.join(X(e.paths,t.name),"verification.md"),state:i}),i})}async function ak(e){return A(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await vr({paths:e.paths,state:t});let r=await co({paths:e.paths,state:t}),i=QI(t,{reason:e.reason}),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),bs({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function ok(e){return A(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await co({paths:e.paths,state:t}),i=ZI(t),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),bs({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function ea(e){return A(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await O(e.paths,e.name);if(mi({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks?await co({paths:e.paths,state:t}):null,i=Yn({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),e.preserveLocalChecks?bs({local:r,state:n,projectRoot:e.paths.projectRoot}):Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function lf(e){if(e.state.verification===null)return"not-applicable";let t=fv.join(X(e.paths,e.state.name),"verification.md");return await Zd({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Li({file:t,state:e.state}),"rebuilt")}import eK from"node:path";ln();Fe();async function sk(e){return A(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await O(e.paths,e.name);mi({state:t,expected:e.expectedContinuation,action:"accept-result"}),await vr({paths:e.paths,state:t});let r=await J(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(ws(r).stateVersion!==r.stateVersion)return Qn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await oe(e.paths,ys(r,t))}let i=UI(t),n=await Be({paths:e.paths,previous:t,next:i});return await le(G(e.paths,t.name),Te({portableState:n,projectRoot:e.paths.projectRoot,branch:Ke(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Li({file:eK.join(X(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as jj}from"node:fs";ln();Fe();Xo();async function fl(e){let t=await O(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 nt({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 can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function ck(e){let t=await BI({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 fl({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function pv(e){let t=await O(e.paths,e.name),r=await Oa(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 J(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 jj.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=ws(n);if(i||a.stateVersion!==n.stateVersion){let o=await Qn({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 jj.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await oe(e.paths,ys(n,t)),{state:t,action:"recorded-final-verification"}}async function hv(e){return A(e.paths,`recover Supervisor final verification ${e.name}`,()=>pv(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}sr();Xo();Z();ot();Fe();var Boe=16*1024;async function uf(e){let t=await cm(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Tn(t.selection.change),t.selection)}function df(e){return Pc(e.projectRoot)}async function mv(e,t){return A(e,`select change ${t}`,async()=>{Tn(t),await Ae(e,t)?await O(e,t):await Me(e,t),await EN(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}async function Tj(e){let t=await uf(e);return t?(await Ae(e,t.change)?await O(e,t.change):await Me(e,t.change),t.change):null}async function ff(e,t){return await nc(e.projectRoot),PN(e.projectRoot,"native",t)}var hf=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]}},pl=class extends Error{state;constructor(t){super("Native canonical Spec changed independently; the merged delta requires fresh verification"),this.name="NativePortableArchiveRequiresReverificationError",this.state=t}};function lk(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function uk(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=Nt.join(e.archiveDir,t);if(!q(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function pf(e){try{return await ze.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function $j(e,t){let r=Nt.normalize(Nt.resolve(e)),i=Nt.normalize(Nt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Oj(e,t){let r;try{r=await ze.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=Nt.join(e.archiveDir,n.name);try{let o=await qt(Nt.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 fk(e,t){let r=await Oa(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Dj(e,t){if(t.status!=="prepared"&&t.status!=="specs-applied")return!1;for(let[r,i]of t.spec_changes.entries()){let n=await lo(e,i.capability);if(i.operation!=="remove"&&(i.expected_target_hash===void 0||i.result_hash===void 0)||i.operation==="remove"&&i.expected_target_hash===void 0)return!0;let a=i.operation==="remove"?null:i.result_hash??(i.content===null?null:rt(i.content));if(r<t.next_spec_index){if(n.hash!==a)return!0;continue}if(n.hash!==a&&!(i.operation==="remove"&&n.hash===null)&&(i.expected_target_hash===void 0||n.hash!==i.expected_target_hash))return!0}return!1}async function Hj(e,t){return await fk(e,t)!==null||await Oj(e,t)!==null}async function ks(e,t){await ze.mkdir(e.transactionsDir,{recursive:!0}),await ve(tn(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Fj(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=Vt(e.paths.projectRoot);r.some(a=>$j(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await te(a);if(!o)continue;let s=await Se(a,o.native.artifact_root);i.some(c=>$j(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 ze.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 qt(Nt.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 is(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 rK(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 lo(e,t){let r=Nt.join(e.specsDir,t),i=Nt.join(r,"spec.md");if(!q(e.specsDir,i))throw new Error("Native canonical spec path escaped");let n;try{n=await ze.lstat(e.specsDir)}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await ze.lstat(r)}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[o,s]=await Promise.all([ze.realpath(e.specsDir),ze.realpath(r)]);if(!q(o,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let c;try{c=await ze.lstat(i)}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!q(s,await ze.realpath(i)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{let l=await z({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1});return{text:l.text,hash:rt(l.text)}}catch(l){if(l.code==="ENOENT")return{text:"",hash:null};throw l}}async function iK(e){let t=Nt.join(e.paths.specsDir,e.change.capability),r=Nt.join(t,"spec.md");if(!q(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let o=await lo(e.paths,e.change.capability);if(e.change.expected_target_hash===void 0){if(o.hash===null)return;throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`)}if(o.hash===null)return;if(o.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let s;try{s=await ze.lstat(e.paths.specsDir)}catch(d){if(d.code==="ENOENT")return;throw d}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let c;try{c=await ze.lstat(t)}catch(d){if(d.code==="ENOENT")return;throw d}if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[l,u]=await Promise.all([ze.realpath(e.paths.specsDir),ze.realpath(t)]);if(!q(l,u))throw new Error("Native canonical capability path escaped");try{let d=await ze.lstat(r);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await ze.unlink(r)}catch(d){if(d.code!=="ENOENT")throw d}await ze.rmdir(t).catch(d=>{if(d.code!=="ENOENT"&&d.code!=="ENOTEMPTY")throw d});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);if(e.change.expected_target_hash===void 0)throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`);let i=await lo(e.paths,e.change.capability),n=e.change.result_hash??rt(e.change.content);if(i.hash===n)return;if(i.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let a=Nt.join(X(e.paths,e.state.name),e.change.source);await Ne(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),await ze.mkdir(t,{recursive:!0}),await Ne(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function pk(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 nK(e,t){let r=X(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){let s=await lo(e,n.capability);i.push({...n,content:null,expected_target_hash:s.hash});continue}let a=await z({root:r,ref:n.source,maxBytes:null,includeHash:!1});if(n.delta_source){let s=await z({root:r,ref:n.delta_source,maxBytes:null,includeHash:!1}),c=Pi(s.text);if(c.capability!==n.capability)throw new Error(`Native delta capability ${c.capability} does not match ${n.capability}`);let l=await lo(e,n.capability),u=yu({currentMarkdown:l.text,delta:c});i.push({...n,content:u.markdown,delta_content:s.text,source_content:a.text,expected_target_hash:l.hash,result_hash:u.result_hash});continue}let o=await lo(e,n.capability);i.push({...n,content:a.text,expected_target_hash:o.hash,result_hash:rt(a.text)})}return i}function aK(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(pk(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function dk(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=Nt.join(e.specsDir,i);if(r.operation==="remove"){if(r.expected_target_hash===void 0&&!await pf(n))continue;let a=await lo(e,r.capability);if(r.expected_target_hash!==void 0&&a.hash===null)continue}else try{if((await z({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 qj(e){let t=[],r=!1,i=[],n=X(e.paths,e.state.name);for(let a of e.state.spec_changes)try{let o=await lo(e.paths,a.capability);if(!a.delta_source){let u=null;if(a.source!==null){let d=await z({root:n,ref:a.source,maxBytes:null,includeHash:!1});u=rt(d.text)}i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:u});continue}let s=await z({root:n,ref:a.delta_source,maxBytes:null,includeHash:!1}),c=Pi(s.text);if(c.capability!==a.capability)throw new Error(`Native delta capability ${c.capability} does not match ${a.capability}`);let l=yu({currentMarkdown:o.text,delta:c});l.rebased&&(r=!0,t.push(`Native canonical Spec changed independently for ${a.capability}; the merged delta requires fresh verification`)),i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:l.result_hash,delta_source:a.delta_source,delta_operations:l.operationResults})}catch(o){t.push(o.message)}return{blockers:t,requiresReverification:r,specPreview:i}}async function hk(e){let t=await O(e.paths,e.name),r=[],i=!1,n;if(t.document_constraints_version===1){let c=await tf({paths:e.paths,state:t});r.push(...c.findings.map(({message:l})=>l))}try{pk(t)}catch(c){r.push(c.message)}let a=await fk(e.paths,e.name);if(a)try{await Dj(e.paths,a)&&(i=!0,r.push("The interrupted Native Archive transaction is missing a safe canonical binding or has drifted; fresh verification is required")),await dk(e.paths,a)}catch(c){r.push(c.message)}if(a===null){try{let l=await Mi({paths:e.paths,state:t});l.drifted&&r.push(l.reason??"Native confirmed requirements changed")}catch(l){r.push(l.message)}let c=await qj({paths:e.paths,state:t});r.push(...c.blockers),i=c.requiresReverification,n=c.specPreview}else n=a.spec_changes.map(c=>({capability:c.capability,operation:c.operation,source:c.source,current_hash:c.expected_target_hash??null,target_hash:c.content===null?null:rt(c.content),...c.delta_source===void 0?{}:{delta_source:c.delta_source},...c.delta_content?{delta_operations:Pi(c.delta_content).operations.map(l=>({id:l.id,operation:l.operation,status:"changed",targetIds:l.operation==="rename"?[l.id,l.to_id]:[l.id]}))}:{}}));let o=t.verification===null?"missing":await Zd({file:Nt.join(X(e.paths,t.name),"verification.md"),stateVersion:t.state_version});o!=="aligned"&&r.push(`verification.md is ${o}`);let s=await Fj({paths:e.paths,state:t});return s.length>0&&r.push(`capabilities are also declared by: ${s.join(", ")}`),{ready:r.length===0,blockers:r,requiresReverification:i,specPreview:n,capabilityPeers:s,archiveDir:uk(e.paths,lk(t)),stateVersion:t.state_version}}async function mf(e){return A(e.paths,`archive portable change ${e.name}`,async()=>{let t=rK(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await fk(e.paths,e.name),i=X(e.paths,e.name),n=await pf(i),a=n?null:await Oj(e.paths,e.name),o;if(n)o=await O(e.paths,e.name);else if(r)o=await qt(Nt.join(uk(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}`);n&&r!==null&&!o.archived&&o.phase==="verify"&&o.verification_result==="pending"&&o.loop.stage==="verify-ready"&&o.state_version>r.start_state_version&&(await ze.rm(tn(e.paths,{kind:"archive",change:e.name}),{force:!0}),r=null);let s=await J(e.paths,e.name);if(n&&!o.archived&&r!==null&&o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&await Dj(e.paths,r)){let f=await ov({paths:e.paths,state:o}),p=await Qn({paths:e.paths,state:f.state,reason:f.rebased?"Native canonical Spec changed independently after Archive preparation; the delta was re-based before fresh verification.":"Native canonical Spec changed after Archive preparation; fresh verification is required before resuming Archive."});throw await ze.rm(tn(e.paths,{kind:"archive",change:e.name}),{force:!0}),new pl(p)}if(n&&!o.archived&&r===null){let f=await Mi({paths:e.paths,state:o});if(f.drifted){let p=f.reason??"Native confirmed requirements changed";throw await Zn({paths:e.paths,state:o,reason:p,keepFailureBudget:!0}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}if(o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&(await qj({paths:e.paths,state:o})).requiresReverification){let h=await ov({paths:e.paths,state:o}),m=await Qn({paths:e.paths,state:h.state,reason:"Native canonical Spec changed independently; the delta was re-based before fresh verification."});throw new pl(m)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await pv({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 J(e.paths,e.name))}let c=uk(e.paths,r?.archive_ref??lk(o)),l=await pf(c);if(r&&aK(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 ff(e.paths,o.name),await ze.rm(je(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)pk(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await Fj({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new hf(f);r={schema:Bh,id:tK(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:lk(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await nK(e.paths,o),created_at:new Date().toISOString()},await ks(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await ks(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 dk(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>Nt.relative(e.paths.projectRoot,Nt.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await nl({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 iK({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await ks(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await ks(e.paths,r)}if(await dk(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await nl({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 en({file:gt(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await ks(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await pf(i)?i:c;if(await Li({file:Nt.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Zd({file:Nt.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 ks(e.paths,r),s&&!d&&(await nl({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await nl({paths:e.paths,state:s,archiveOwnedPaths:u}),await ze.mkdir(e.paths.archiveDir,{recursive:!0}),await pf(c))throw new Error(`Native Archive target already exists: ${c}`);await ze.rename(i,c),r={...r,status:"moved"},await ks(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await ff(e.paths,o.name),await ze.rm(je(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await ze.rm(tn(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}})}uc();Ya();function gr(e,t,r){return e.language==="zh-CN"?r:t}function oK(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});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:gr(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:gr(e,"Reply A or B","回复 A 或 B"),agentInstruction:gr(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 i(gr(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 i(gr(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}: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 a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"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:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,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."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:gr(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:gr(e,"Accept the result","接受结果"),agentInstruction:gr(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。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=Mn)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(gr(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(gr(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 sK(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 cK(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:gr(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:gr(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Vj(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Ss(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Lj(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function lK(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Mj(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function uK(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function dK(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 uo(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Vj({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Ss("summary","--summary"),lK(e.name,e.flag)]}}function Bj(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:gr(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function fK(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function vv(e){return[uo({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),uo({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function pK(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function L(e,t,r={}){let i=uK(t)&&e.coordination_mode===void 0,n=oK(e,i,t),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:[Ss("summary","--summary")],commandAlternatives:[uo({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:[Ss("summary","--summary")],commandAlternatives:[uo({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...vv({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:[Ss("summary","--summary")],commandAlternatives:[uo({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),uo({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:[Ss("summary","--summary")],commandAlternatives:[uo({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...vv({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:[Ss("summary","--summary")],commandAlternatives:vv({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:vv({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},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?Vj({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:dK({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?[Mj("coordination-mode","--coordination-mode",Oh)]:[]],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:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],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}],verification_checks:[Lj()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:h})=>h==="verified");if(s){let h=r.supervisorIntegrationRetryIds;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}],...h&&h.length>0?{retry_check_ids:[...h]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:h})=>h==="blocked"||h==="needs-reverify"),l=t.children.some(({status:h})=>h==="needs-reverify"),u=t.children.some(({status:h})=>h==="ready"||h==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(h=>h.status==="blocked"&&(h.builderFailureCount??0)>=Mn)??null,f=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:gr(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[Ss("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}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=Lj();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${gr(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:pK([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"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:r.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:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):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;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Bj(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>fK(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Bj(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Mj("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...cK(e)],userCommunication:sK(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[uo({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")}}import{randomUUID as hK}from"node:crypto";import{promises as hl}from"node:fs";import Yj from"node:path";Oe();Ht();Fe();eN();Xo();$h();sr();Z();var mk=["evidence.md","repair.md","archive.md","checkpoint.md"],mK="verification.md";async function vK(e){try{return await hl.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function vk(e,t){let r=pe(e,t),i=[tn(e,{kind:"migration",change:t}),Lo(e,t),...mk.map(n=>Yj.join(r,n))];return(await Promise.all(i.map(vK))).some(Boolean)}async function gK(e,t){let r=await Oa(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Wj(e,t){await hl.mkdir(e.transactionsDir,{recursive:!0}),await ve(tn(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function zj(e,t,r={}){let i=r.removeVerificationReport===!1?mk:[...mk,mK];await Promise.all([hl.rm(je(e,t),{recursive:!0,force:!0}),hl.rm(Lo(e,t),{recursive:!0,force:!0}),...i.map(n=>hl.rm(Yj.join(pe(e,t),n),{force:!0}))])}async function Jj(e,t){await le(G(e,t.name),Te({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Gj(e,t){try{let r=await Gt(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 Kj(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ie(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 wK(e){let t=pe(e.paths,e.state.name),r=await z({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 z({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return jh({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Uj(e,t){let r=await is(e,t);if(r.status==="runtime-incompatible")throw new Fr(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Bi(e){return A(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await gK(e.paths,e.name),r=await Ae(e.paths,e.name)?await qt(gt(e.paths,e.name)):null;if(!t&&r)return await zj(e.paths,e.name,{removeVerificationReport:!1}),await Jj(e.paths,r),r;let i=null,n=null;for(t||(i=await Uj(e.paths,e.name),n=await Gj(e.paths,e.name),Kj(e.paths,n),t={schema:Mh,id:hK(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Wj(e.paths,t));;){let a=hC(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Uj(e.paths,e.name),n??=await Gj(e.paths,e.name),Kj(e.paths,n),r=pC({state:i,acceptance:await wK({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await pc(gt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await zj(e.paths,e.name):a.action==="commit-transaction"&&(r??=await qt(gt(e.paths,e.name)),await Jj(e.paths,r)),t={...t,status:a.nextStatus},await Wj(e.paths,t)}return await hl.rm(tn(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??qt(gt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Qj}from"node:fs";import Zj from"node:path";Fe();import{promises as gk}from"node:fs";import yK from"node:path";Qe();var NK=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),bK=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),kK=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),SK=new Set(["status","summary"]);function gv(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function wv(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function EK(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Es(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function RK(e,t,r,i){let n=gv(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=wv(n,NK,"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=gv(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=wv(o,bK,"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=gv(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=wv(c,SK,"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=gv(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:h,...m}=f,v=wv(m,kK,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],w=g.covers.length>0?g.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||h!==void 0&&h!==j("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||!EK(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let k=g.depends_on.length===0?"ready":"pending";if(f.status!==k)return`Native Supervisor child ${g.name} has progressed beyond its initial ${k} 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((f.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function mn(e){let t=ss(e.paths,e.state.name),r;try{let c=await gk.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Es(t,"","Native Supervisor overlay is not a regular file");r=await gk.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Es(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Es(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=yK.join(e.paths.changesDir,e.state.name),a;try{a=await It({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Es(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 J(e.paths,e.state.name)}catch(c){return Es(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Es(t,r,"Native Supervisor overlay disappeared during inspection");let s=RK(i,e.state,a.contract,o);return s?Es(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 Xj(e){let t=await mn({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 gk.rm(t.file,{force:!1})}sr();$a();function wk(e,t){let r=ie(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 PK(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function xK(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:we(t),completed_at:i});return re({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?PK(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 CK(e){try{let t=await lt(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 Rs(e){return A(e.paths,`recover portable change ${e.name}`,async()=>{let t=await O(e.paths,e.name);if(t.status==="done")return await lf({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=wk(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await mn({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 Xj({paths:e.paths,state:t,expected:i}),n=!0);let a=G(e.paths,e.name),o=await CK(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let m=o.local.execution,v=await ul(o.local),g=m.stage==="verifying"&&m.actor==="verifier"&&m.executionId!==null,w=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&m.stage==="checking"&&m.actor==="runtime";if(g||v!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?m.verifierStartedAt===void 0&&m.requestCheckRounds===0?`Native Verifier execution ${m.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${m.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await le(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await lf({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(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=Yn({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await en({file:gt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await Qj.rm(Zj.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=Te({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await le(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,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 m=xK(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 en({file:gt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let p=Te({portableState:t,projectRoot:e.paths.projectRoot,branch:ie(e.paths.projectRoot).currentBranch});await Qj.mkdir(Zj.dirname(G(e.paths,t.name)),{recursive:!0}),await le(a,p,{containedRoot:e.paths.runtimeDir}),await lf({paths:e.paths,state:t});let h=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:p,action:f?"reverify":"resume-stable-boundary",reason:s,message:h??(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.`)}})}Xo();Oe();bh();fr();import{randomUUID as OK}from"node:crypto";import{accessSync as DK,constants as HK,promises as xs}from"node:fs";import Yr from"node:path";ls();bh();var _K=6e4,jt=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function yk(e,t){try{return Qi("gh",t,{cwd:e,timeoutMs:_K}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function Nk(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function bk(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function eT(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ps(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function tT(e,t){let r=Ps(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 Nv(e,t){let r=Ps(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 rT(e,t){let r=Nk(e,t);if(Ps(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:eT(r.number,`${t}.number`),url:tT(r.url,`${t}.url`),baseBranch:Ps(r.baseRefName,`${t}.baseRefName`),headBranch:Ps(r.headRefName,`${t}.headRefName`),headSha:Nv(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function AK(e){let t=Nk(e,"pull request finish provider output.pullRequest");return{number:eT(t.number,"pull request finish provider output.pullRequest.number"),url:tT(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Ps(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Ps(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Nv(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function IK(e){let t=Nk(bk(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=AK(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function kk(e){let t=yk(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=bk(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:rT(r[0],"gh pr list output[0]")}function iT(e){let t=yk(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=rT(bk(t,"gh pr view output"),"gh pr view output"),i=Nv(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new jt("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new jt(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new jt(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new jt(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function yv(e){try{return kk(e)}catch{return null}}function jK(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 TK(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=yk(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=kk(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new jt("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof jt)throw n;let a=yv(e);if(!a)throw new jt(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=iT({...e,pullRequest:t})}catch(n){throw n instanceof jt?n:new jt(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function $K(e){let[t,...r]=e.config.command,i;try{let o=Qi(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${jK(e)}
|
|
320
|
+
`}).trim();i=IK(o)}catch(o){if(o instanceof jt)throw o;let s=yv(e)??e.existingPullRequest;throw new jt(`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!==Nv(e.headSha,"Native Archive head SHA")){let o=yv(e)??e.existingPullRequest;throw new jt("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=iT({...e,pullRequest:n})}catch(o){if(o instanceof jt)throw o;let s=yv(e)??e.existingPullRequest??n;throw new jt(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function nT(e){let t=kk(e);return e.config?$K({...e,existingPullRequest:t,config:e.config}):TK({...e,existingPullRequest:t})}var Cs="comet.native.workspace-finish.v1",oT="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sT=new RegExp(`^${oT}$`,"u"),FK=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function cT(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Cs||typeof t.name!="string"||!sT.test(t.name)||typeof t.transactionId!="string"||!FK.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Yr.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:Cs,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function bv(e,t){if(!sT.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Yr.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function ta(e,t,r={}){let i=bv(e,t);try{let n=await xs.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=cT(JSON.parse(await xs.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function kv(e,t={}){let r;try{r=await xs.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.isFile()&&!n.isSymbolicLink()||n.isDirectory())continue;let a=new RegExp(`^workspace-finish-(${oT})\\.json$`,"u").exec(n.name);if(!a)continue;let o=await ta(e,a[1],t);o&&i.push(o)}return i}async function Ek(e,t){let r=bv(e,t),i=Yr.join(e.transactionsDir,`workspace-finish-invalid-${t}-${OK()}.json`);try{return await xs.lstat(r),await xs.rename(r,i),i}catch(n){if(n.code==="ENOENT")return null;throw n}}async function _s(e,t){let r=cT(t);await ve(bv(e,r.name),r,{containedRoot:e.transactionsDir})}async function vl(e,t){try{await xs.unlink(bv(e,t))}catch(r){if(r.code!=="ENOENT")throw r}}var ml=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},Vi=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 Rk(e,t){let r=Yr.relative(e,t);return r===""||!Yr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Yr.sep}`)}function fo(e,t){let r=Yr.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||Yr.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function Sk(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function qK(e,t,r,i=[]){let n=[...zc(e.projectRoot)?[".comet/config.yaml"]:[],fo(e.projectRoot,pe(e,t.name)),fo(e.projectRoot,df(e))];r&&n.push(fo(e.projectRoot,r));for(let a of r?t.spec_changes:i)n.push(fo(e.projectRoot,Ja(e,a.capability)));return n}function LK(e,t){let r=Ln(e).filter(i=>!Sk(i,t));if(r.length>0)throw new Vi(r,e)}function MK(e,t){return t.map(r=>Yr.resolve(e,...r.split("/")))}function BK(e){let t=Ln(e).filter(r=>!(r===".comet/config.yaml"&&zc(e)));if(t.length>0)throw new Vi(MK(e,t),e,`Native merge target worktree is not clean: ${e}`)}function lT(e){return e.split("\0").filter(Boolean)}function VK(e,t){return lT(_(e,["ls-files","-z","--",t]))}function WK(e,t){return lT(_(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function aT(e){try{if(_(e,["config","--get","user.name"])&&_(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function zK(e,t){for(let r of Vt(e))if(ie(r).currentBranch===t)return r;return null}function JK(e,t){try{Qi(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function GK(e,t){if(!t)return;let r=t.command[0];try{if(Yr.posix.isAbsolute(r)||Yr.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=Yr.resolve(e,r);if(!Rk(e,n))throw new Error("configured executable escapes the project root");DK(n,HK.X_OK);return}Qi(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 vf(e){let{paths:t,state:r}=e,i=r.workspace,n=ie(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");return aT(t.projectRoot),{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`);aT(t.projectRoot);let a=qK(t,r,e.archiveDir,e.appliedSpecChanges);i.finish!=="keep"&&LK(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:zK(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}`);BK(o)}let s=i.finish==="push"||i.finish==="pull-request"?G_(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(JK("gh",["--version"]),GK(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 KK(e){try{return await xs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function UK(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,diagnosticArgs:null,recoveryArgs:null}}async function YK(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(Rk(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await Id(e.changeRoot),_(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function Pk(e){let t=UK(e.plan),r=null;try{let i=[fo(e.paths.projectRoot,pe(e.paths,e.name)),fo(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(d=>fo(e.paths.projectRoot,Ja(e.paths,d.capability))),fo(e.paths.projectRoot,df(e.paths))],n=e.plan.isolation==="current"||e.plan.finish==="keep",a=Ln(e.plan.changeRoot).filter(d=>!Sk(d,i)&&!(d===".comet/config.yaml"&&zc(e.plan.changeRoot)));if(a.length>0&&!n)throw t.blockedPaths=a,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${a.join(", ")}`);let o=[],s=new Set;for(let d of i){let f=Yr.resolve(e.paths.projectRoot,...d.split("/"));if(VK(e.plan.changeRoot,d).length>0&&o.push(d),await KK(f))for(let h of WK(e.plan.changeRoot,d))s.add(h)}if(o.length>0&&_(e.plan.changeRoot,["add","-u","--",...o]),s.size>0&&_(e.plan.changeRoot,["add","--",...s]),_(e.plan.changeRoot,["diff","--cached","--name-only","-z","--",...i])){let d=[...new Set([...o,...s])];_(e.plan.changeRoot,n?["commit","--only","-m",`chore(native): archive ${e.name}`,"--",...d]:["commit","-m",`chore(native): archive ${e.name}`])}t.commit=_(e.plan.changeRoot,["rev-parse","HEAD"]);let l=Ln(e.plan.changeRoot).filter(d=>Sk(d,i));if(l.length>0)throw new Error(`Native archive commit left change-owned working-tree changes: ${l.join(", ")}`);if(!n&&!zr(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"){_(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=nT({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 d=Rk(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!d?(await Id(e.plan.changeRoot),_(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 u=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(_(u,["switch",e.plan.targetBranch]),r=u),_(u,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=u,t.cleanup=await YK(e.plan),t}catch(i){if(i instanceof jt&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{_(r,["merge","--abort"])}catch{}try{ie(r).currentBranch===e.plan.targetBranch&&_(r,["switch",e.plan.changeBranch]),n=ie(r).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=r)}throw t.status="blocked",t.message=i.message,t.diagnosticArgs=["git","-C",e.plan.finish==="merge"&&t.targetRoot?t.targetRoot:e.plan.changeRoot,"status","--short"],t.recoveryArgs=["comet","native","archive",e.name,"--confirmed"],new ml(t)}}Z();var Ck=Ji(Ri(),1);fr();Qe();Ht();sr();import{promises as XK}from"node:fs";import xk from"node:path";var Sv=class extends Error{};async function gf(e,t){let r=await z({root:e.nativeRoot,ref:xk.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,Ck.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new Sv("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:re(i)}}async function dT(e,t,r){let i;try{i=await XK.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return[];throw a}if(i.length>4096)throw new Error("Native archive discovery exceeds 4096 records");let n=[];for(let a of i){if(!a.isDirectory()||a.isSymbolicLink())continue;let o=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(a.name)?.[1];if(r!==void 0&&o!==void 0&&o!==r)continue;let s=xk.join(e.archiveDir,a.name,"comet-state.yaml");try{let c=await gf(e,s);c.state.archived&&c.state.status==="done"&&n.push(c)}catch(c){if(c.code==="ENOENT"||c instanceof Sv)continue;let l=a.name.replace(/^\d{4}-\d{2}-\d{2}-/u,"");t?.(l,`Native archive ${a.name} is unreadable: ${c.message}`)}}return n}function Ev(e){return j("comet.native.status-record.v1",e)}function uT(e){let t=xk.relative(e.projectRoot,e.file).replaceAll("\\","/");try{let r=_(e.projectRoot,["log","-1","--format=%H","HEAD","--",t]);if(!r)return null;let i=re((0,Ck.parse)(_(e.projectRoot,["show",`${r}:${t}`])));return Ev(i)===Ev(e.state)?r:null}catch{return null}}function fT(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=uT(e),i=uT(t);if(!r||!i)return!1;try{return _(e.projectRoot,["merge-base","--is-ancestor",i,r]),!0}catch{return!1}}function pT(e,t){return e.state.archived&&t.state.archived&&Ev(e.state)===Ev(t.state)}Cu();import Cf from"path";import{realpathSync as xY}from"fs";function wf(e){return e.charCodeAt(0)===65279?e.slice(1):e}function hT(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var ra={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mT(e){return e?e.command?`${ra.next} ${e.command}`:e.ask_user?`${ra.next} ${e.ask_user}`:null:null}function vT(e,t){let r=[e.summary],i=mT(e.next);return i&&r.push(i),e.user_message&&r.push("",ra.relay,e.user_message),t!==void 0&&r.push("",ra.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
321
321
|
`)}
|
|
322
322
|
`}function gT(e,t,r){let i=[e.summary],n=mT(e.next);return n&&i.push(n),e.user_message&&i.push("",ra.relay,e.user_message),i.push("",`${ra.detail} ${t}`),r!==void 0&&i.push("",ra.details,JSON.stringify(r,null,2)),i.join(`
|
|
323
|
-
`)}import{promises as F$}from"fs";import El from"path";import{isDeepStrictEqual as lY}from"util";import{createHash as XK}from"crypto";function wT(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 yT(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))yT(e[t]);return Object.freeze(e)}function po(e){return yT(structuredClone(e))}function _k(e,t,r,i){return e.resolveStep({pkg:po(t),state:po(r),context:po(i)})}function NT(e,t,r,i,n,a){return e.resolveNext({pkg:po(t),state:po(r),step:po(i),outcome:po(n),context:po(a)})}function QK(e,t,r){return XK("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function Ak(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function bT(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=_k(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=Ak(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:QK(s.runId,s.iteration,o.id),stepId:o.id};return ZK(e,s,c,r)}function ZK(e,t,r,i){let n=wT(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 kT(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"?_k(i,e,t,n):void 0,o=a?Ak(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"?NT(i,e,t,o,r,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Ak(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as q6}from"node:fs";import S$ from"node:path";Qe();import ST from"node:path";var eU="comet.native.archive-preflight.v1",tU="comet.native.archive-preflight.v1",rU="comet.native.archive-operation.v1",iU=/^[a-f0-9]{64}$/u,ET=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nU=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Rv(e,t){return e<t?-1:e>t?1:0}function aU(e,t){if(typeof e!="string"||!iU.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ia(e,t){return e===null?null:aU(e,t)}function oU(e,t){let r=ST.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ST.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 sU(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function cU(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 lU(e,t){if(!ET.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=ia(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=ia(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=ia(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 uU(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:ia(e.contractHash,"Native archive contract hash"),acceptanceHash:ia(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:ia(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:ia(e.reportHash,"Native archive report hash"),envelopeHash:ia(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:ia(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 dU(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!nU.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(Rv);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function fU(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(Rv)}function RT(e){if(!ET.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(lU).sort((l,u)=>Rv(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:j(rU,l)})),i=uU(e.evidence),n=cU(e.workspace),a=[...new Set([...dU(e.findingCodes??[]),...fU({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(Rv),o=sU(e.revision),s=oU(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:eU,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:j(tU,c)}}Ht();Qe();import{createHash as pU}from"node:crypto";import PT from"node:path";var hU="comet.native.conflict-radar.v1",Cr=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}),mU="comet.native.conflict-radar.v1",vU="comet.native.conflict-radar-signals.v1",gU=/^[a-f0-9]{64}$/u,_T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wU=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),yU=new Set(["capability","operation","baseHash"]),NU=new Set(["path","kind"]);function gl(e,t){return e<t?-1:e>t?1:0}function Ik(e){return Buffer.byteLength(e,"utf8")}function jk(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 Tk(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(Ik(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function bU(e,t){let r=Tk(e,t,Cr.maxArtifactPathBytes),i=PT.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)||PT.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 AT(e,t){if(typeof e!="string"||!gU.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kU(e,t){let r=jk(e,yU,t),i=Tk(r.capability,`${t} capability`,Cr.maxCapabilityBytes);if(!_T.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:AT(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 SU(e,t){let r=jk(e,NU,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:bU(r.path,`${t} path`),kind:r.kind}}function EU(e,t){let r=jk(e,wU,`Conflict radar change ${t}`),i=Tk(r.name,`Conflict radar change ${t} name`,Cr.maxNameBytes);if(!_T.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>Cr.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>Cr.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>kU(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>gl(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)=>SU(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>gl(c.path,l.path)||gl(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:AT(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function RU(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Cr.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(EU).sort((n,a)=>gl(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)>Cr.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Cr.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function PU(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 xU(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 CU(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function _U(e,t){let r=[],i=pU("sha256").update(`${vU}
|
|
324
|
-
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Lu(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Cr.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(PU(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=xU(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:CU(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function xT(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function AU(e,t){return xT(e.classification)-xT(t.classification)||gl(e.left,t.left)||gl(e.right,t.right)}function CT(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:hU,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 IT(e){let t=RU(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(_U(t[s],t[c]));r.sort(AU);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(mU,{changes:t,relationships:i}),a=r.slice(0,Cr.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=CT(t,r,a,n);for(;a.length>0&&Ik(JSON.stringify(o))>Cr.maxSerializedBytes;)a=a.slice(0,-1),o=CT(t,r,a,n);if(Ik(JSON.stringify(o))>Cr.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}hi();cr();var IU=4096;async function jU(e,t=Cr.maxChanges){try{let r=await Er({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 jT(e,t){let r=await Me(e,t),[i,n]=await Promise.all([r.implementation_scope?rl(e,t,r.implementation_scope):null,Gt(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 Pv(e,t,r={}){let n=(await jU(e,IU)).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 jT(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await jT(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=IT([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"]:[]]}}ot();Z();import{promises as UU}from"fs";import YU from"path";import{isDeepStrictEqual as _v}from"util";Oe();ci();zo();Fe();Z();cr();Bn();Qe();Qe();var wl={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var TU=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function $U(e,t){return e<t?-1:e>t?1:0}function OU(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"||!TU.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort($U)}function $k(e=[]){return OU(e,"Native repair failed check IDs",wl.maxFailedCheckIds,!0)}function TT(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function DU(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:TT(e.failedAcceptanceIds,t.failedAcceptanceIds)&&TT(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ok(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(DU(i,a))break;r+=1,i=a}return r}Md();Wn();function xv(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 $T="repairStagnation",Xr={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},FU=/^[a-f0-9]{64}$/u;var qU=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),LU=["data","runId","sequence","timestamp","type"],OT=["disposition","overrideSummaryHash","signatureHash"],MU=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],DT=12;function Hk(e,t){return e<t?-1:e>t?1:0}function HT(e,t,r){let i=Object.keys(e).sort(Hk);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Cv(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 yf(e,t){if(typeof e!="string"||!FU.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function BU(e){if(!Array.isArray(e)||e.length>wl.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(Hk)}function FT(e){if(typeof e!="string"||e.length===0||e.length>Xr.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 Dk(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Xr.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xr.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>Xr.maxTextCharacters&&(!n||e.length>Xr.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Xr.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>Xr.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Dk(s,t+1,r,`${i}[${c}]`));return}let a=Cv(e,i),o=Object.keys(a);if(o.length>Xr.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xr.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Xr.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Dk(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function VU(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 WU(e,t,r){let i=Cv(e,`Native repair trajectory event ${t+1}`);if(HT(i,LU,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(VU(i.timestamp),typeof i.type!="string"||!qU.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(FT(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 Dk(i.data,0,n,"Native trajectory event data"),Cv(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Fk(e){let t=Cv(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Hk),i=r.length===OT.length&&r.every((l,u)=>l===OT[u]);i||HT(t,MU,"Native repair trajectory projection");let n=yf(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:yf(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=yf(t.contractHash,"Native repair trajectory contract hash"),s=BU(t.failedAcceptanceIds),c=$k(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 zU(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 JU(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??DT;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ok({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<wl.warningAtConsecutiveFailures?"continue":a<wl.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function GU(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??DT;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 qT(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xr.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=FT(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=WU(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xr.maxTotalDataNodes||c>Xr.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?yf(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?yf(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,$T)){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 h=Fk(f[$T]);if(zU(f,h),h.overrideSummaryHash===null)h.contractHash!==null&&a!==null&&h.contractHash!==a&&(r.length=0,o=0),h.contractHash!==null&&(a=h.contractHash),h.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),JU(h,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:h.signatureHash,...h.contractHash===null?{}:{failedAcceptanceIds:[...h.failedAcceptanceIds],failedCheckIds:[...h.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");GU(h,r,i);let m=r.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:h.signatureHash,summaryHash:h.overrideSummaryHash})}if(i=h,r.length>wl.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function LT(e){return qT(e).history}function MT(e){let t=qT(e).latestProjection;return t?{...t}:null}ci();var vn={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:[]},Nf=ae("comet-native-runtime:v3:scope-reopen"),KU=[{skillVersion:"3",skillHash:ae("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ae("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ae("comet-native-runtime:v1")}];function BT(e){return e.skillVersion===vn.definition.metadata.version&&e.skillHash===Nf||KU.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var qk={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}};ci();async function ho(e){let r={sequence:(await dr(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 E_(e.changeDir,e.run.trajectoryRef,r),r}async function As(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:ae(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await R_(e.changeDir,e.run.checkpointRef,t),t}ci();function VT(e){return ae(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}))}cc();var XT=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],XU=new Set(XT),QT=new Set([...XT,"minimum_runtime_version","revision"]),QU=new Set([...QT,"operation"]),Lk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),ZU=new Set([...Lk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),bf=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 Yt(e,t){return YU.join(Q(e,t),"transition.json")}function e6(e){return`transition-${e}`}async function t6(e,t,r){let i=e6(t);return An(e,i,r)}async function wn(e,t,r,i){let n=await t6(e,t,r);try{return await i()}finally{await In(n)}}function Iv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Bk(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 Av(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gn(e,t){return _v(e,t)}function Mk(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=>!ZU.has(u)),a=[...Lk].find(u=>!Object.hasOwn(r,u)),o=Lk.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(xv(r.summary,"Native transition journal event summary"),Rt(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&&(xv(r.noCodeReason,"Native transition journal event no-code reason"),Rt(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")?Fk(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 r6(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 Mk({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mk(e,t)}function Vk(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?r6(e.eventData,e.evidenceHash):Mk(e.eventData,e.evidenceHash),n=Wa(e.nextRun),a=e.previousRun===null?null:Wa(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function WT(e,t,r=!1){if(e.skill!==vn.definition.metadata.name||(r?!BT(e):e.skillVersion!==vn.definition.metadata.version||e.skillHash!==Nf)||e.orchestration!==vn.definition.orchestration.mode||e.pendingRef!==Lr.pendingRef||e.trajectoryRef!==Lr.trajectoryRef||e.contextRef!==Lr.contextRef||e.artifactsRef!==Lr.artifactsRef||e.checkpointRef!==Lr.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function zT(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 JT(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 Wk(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(WT(o,"next Run",i||a!==null),JT(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(WT(a,"previous Run",!0),JT(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(!_v(zT(a),zT(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function i6(e,t,r){return ae(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function ZT(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function GT(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function zk(e,t,r,i,n=!1){let a=r.eventData,o=GT(e),s=GT(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&&_v(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&&_v(e.spec_changes,t.spec_changes),l=VT({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=i6(e.name,a.summary,t.spec_changes),l=ae(`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 Jk(e,t){let r=Iv(e);if(Bk(r,QU),r.schema!==ja)throw new Error(`Expected Native transition schema ${ja}`);let i=Av(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 ${ja} minimum_runtime_version must be ${3}`);let n=Av(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=Vk(r,t),o=zt(r.previousState),s=zt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(zk(o,s,a,r.operation),Wk(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:ja,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 n6(e,t){let r=Iv(e);if(Bk(r,XU),r.schema!==Jo)throw new Error(`Expected Native transition schema ${Jo}`);let i=Vk(r,t,!0),n=Ta(r.previousState),a=Ta(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return zk(n,a,i,ZT(n,a,i.eventData),!0),Wk(n,a,i,!0),{schema:Jo,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 Gk(e,t){let r=Iv(e);if(Bk(r,QT),r.schema!==jn)throw new Error(`Expected Native transition schema ${jn}`);if(Av(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${jn} minimum_runtime_version must be 2`);let n=Av(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Vk(r,t,!0),o=Ii(r.previousState),s=Ii(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(zk(o,s,a,ZT(o,s,a.eventData),!0),Wk(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:jn,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 a6(e,t){let r=Iv(e);if(r.schema===ja)return{status:"current",journal:Jk(r,t)};if(r.schema===Jo)return{status:"migration-required",journal:n6(r,t)};if(r.schema===jn)return{status:"migration-required",journal:Gk(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function Kk(e,t){let r=Yt(e,t),i=B(e,r);await T(i,r);try{let n=await ht({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return a6(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function na(e,t){let r=await Kk(e,t);if(!r)return null;if(r.status==="migration-required")throw new bf(t);return r.journal}function KT(e,t){if(gn(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(gn(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function UT(e,t){if(gn(e,t.nextState))return"next";if(gn(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function o6(e){let{journal:t}=e;return e$({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 e$(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function YT(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=o6({sequence:a.index+1,journal:t,type:a.event.type});if(!gn(e$(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 yl(e,t,r){if(await Tc(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await hm(e,t);let i=await na(e,t);if(!i)return null;let n=Q(e,t),a=YT(await dr(n,i.nextRun.trajectoryRef),i),[o,s]=await Promise.all([At(n),Me(e,t)]),c=KT(o,i),l=UT(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 rs(n,i.nextRun),await r?.afterRunStateWritten?.(i)),!gn(await At(n),i.nextRun))throw new Error(`Native transition Run content changed while continuing ${i.change}; recovery journal was preserved`);if(l==="previous"){let v=await ld(e,i.nextState,i.previousState.revision);if(!gn(v,i.nextState))throw new Error(`Native transition change write diverged for ${i.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(i)}if(!gn(await Me(e,t),i.nextState))throw new Error(`Native transition change content changed while continuing ${i.change}; recovery journal was preserved`);let u=await na(e,t);if(!u||!gn(u,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was preserved`);let d=YT(await dr(n,i.nextRun.trajectoryRef),i);i.previousRun===null&&(d.started||await ho({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 ho({changeDir:n,run:i.nextRun,type:"state_transitioned",data:{...i.eventData,transitionId:i.id},now:new Date(i.createdAt)})),await As({changeDir:n,run:i.nextRun,trajectoryOffset:f.sequence,evidenceHash:i.evidenceHash,now:new Date(i.createdAt)});let[p,h]=await Promise.all([At(n),Me(e,t)]);KT(p,{...i,previousRun:i.nextRun}),UT(h,{...i,previousState:i.nextState});let m=await na(e,t);if(!m||!gn(m,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was not removed`);return await UU.rm(Yt(e,t),{force:!0}),i.nextState}async function t$(e,t,r){return A(e,`continue transition ${t}`,()=>wn(e,t,`continue transition ${t}`,()=>yl(e,t,r)))}Vu();Ht();Ht();Vu();Qe();import r$ from"node:path";var s6="comet.native.contract.v1",c6="comet.native.acceptance-set.v1",i$=/^[a-f0-9]{64}$/u,kf={maxAcceptanceCriteria:Bu.maxCriteria};function n$(e,t){let r=r$.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})||r$.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 a$(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
325
|
-
`))}function l6(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(i$))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(i$))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=n$(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:a$(e.markdown)},markdown:e.markdown}}function u6(e,t){return o$(e.id,t.id)}function o$(e,t){return e<t?-1:e>t?1:0}function s$(e){let t=n$(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(l6).sort((d,f)=>o$(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=Ah(e.briefMarkdown,t,kf.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Ih(f,d.source,kf.maxAcceptanceCriteria-a.length)),a.push(...oC(f,d.source,kf.maxAcceptanceCriteria-a.length)));if(a.sort(u6),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>kf.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${kf.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:a$(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(c6,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(s6,u)}}var jv={maxSpecs:64};async function aa(e){if(e.specChanges.length>jv.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await z({root:e.changeDir,ref:e.briefRef,maxBytes:null}),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 z({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:s$({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}hi();Ba();Wn();Md();import{execFile as E6}from"node:child_process";Nh();eb();import{promisify as R6}from"node:util";import{promises as g6}from"fs";Oe();import Nl from"path";ci();Z();cr();Ll();Bn();var Sf={maxArtifacts:128},bl=/^[a-f0-9]{64}$/u;function Tv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $v(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 mo(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 c$(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Uk(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function d6(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Nl.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Nl.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Yk(e,t){return Nl.join(Q(e,t),"checkpoints","progress.json")}function vo(e,t){return Nl.join(Q(e,t),"checkpoint-journal.json")}function Xk(e,t,r){if(!bl.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Nl.join(Q(e,t),"checkpoints","manifests",`${r}.json`)}function f6(e){if(!bl.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Qk(e,t,r){let i=await ht({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function p6(e,t){let r=Tv(e,`checkpoint manifest artifact ${t}`);$v(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=d6(mo(r.path,`checkpoint artifact ${t} path`,4096)),n=Ki(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!bl.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Uk(r.size,`checkpoint artifact ${t} size`)}}function Ov(e,t){let r=Tv(e,"Native checkpoint manifest");if($v(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>Sf.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(p6),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=Uk(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Zk(e){return ae(JSON.stringify(Ov(e,e.change)))}function eS(e,t){let r=Tv(e,"Native progress checkpoint");if($v(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=c$(r.previousRevision,"Native checkpoint previousRevision"),a=c$(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=mo(r.manifestHash,"Native checkpoint manifestHash",64);if(!bl.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=f6(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=mo(r.inputHash,"Native checkpoint inputHash",64);if(!bl.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=mo(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Uk(r.artifactCount,"Native checkpoint artifactCount");if(u>Sf.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=mo(r.summary,"Native checkpoint summary"),f=mo(r.nextAction,"Native checkpoint nextAction");if(Rt(d)!==d||Rt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:mo(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 h6(e,t){let r=Tv(e,"Native checkpoint journal");if($v(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=zt(r.previousState),n=zt(r.nextState),a=eS(r.checkpoint,t),o=Ov(r.manifest,t),s=mo(r.inputHash,"Native checkpoint journal inputHash",64),c=ae(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!bl.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!==Zk(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 m6(e,t,r){let i=Nl.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=Rg(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Qo({root:e.projectRoot,file:i,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 v6(e,t){let r=Yk(e,t),i=B(e,r);await T(i,r);try{return eS(await Qk(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function tS(e,t,r){let i=Xk(e,t,r),n=B(e,i);await T(n,i);let a=await Qk(n,i,"Native checkpoint manifest"),o=Ov(a,t);if(rS(e,o),Zk(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function go(e,t){let r=vo(e,t),i=B(e,r);await T(i,r);try{let n=h6(await Qk(i,r,"Native checkpoint journal"),t);return rS(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function l$(e,t,r,i){let n=Ov(r,t);rS(e,n);let a=Zk(n),o=Xk(e,t,a),s=B(e,o);await T(s,o);try{let c=await tS(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 ve(o,n,{containedRoot:s,beforeCommit:i?.beforeCommit}),a}function rS(e,t){for(let r of t.artifacts){let i=Rg(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function u$(e,t){let r=eS(t,t.change),i=await tS(e,r.change,r.manifestHash),n=ae(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=Yk(e,t.change),o=B(e,a);await T(o,a),await ve(a,r,{containedRoot:o})}async function d$(e){let t;try{t=await v6(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:Yk(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 tS(e.paths,e.name,t.manifestHash);let a=ae(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 m6(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:Xk(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}Fe();async function iS(e,t,r){let i=await go(e,t);if(!i)return null;if(await l$(e,i.change,i.manifest)!==i.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ld(e,i.nextState,i.previousState.revision,{allowPendingCheckpointRecovery:!0}),await r?.afterStateWritten?.(i),await u$(e,i.checkpoint),await r?.afterProgressWritten?.(i),await g6.rm(vo(e,t),{force:!0}),i}async function f$(e,t,r){return A(e,`continue checkpoint ${t}`,()=>wn(e,t,`continue checkpoint ${t}`,async()=>(await yl(e,t),iS(e,t,r))))}async function Ef(e,t){await yl(e,t),await iS(e,t)}Oe();Qc();Z();ei();import{constants as nS,promises as vi}from"node:fs";import kl from"node:path";var w6=/^[a-f0-9]{64}$/u,y6=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function N6(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Dv(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Tr(r,i)?ne(r,i):ne(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function b6(e,t){let r=kl.resolve(e),i=kl.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["",...kl.relative(r,i).split(kl.sep).filter(Boolean)]){o&&(a=kl.join(a,o));let s=await vi.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await vi.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 p$(e){for(let t of e){let r=await vi.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!N6(t,r)||await vi.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function h$(e){if(!w6.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function k6(e){let t=y6.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function m$(e,t,r){return Ia(Q(e,t),h$(r))}async function S6(e,t,r){let i=await b6(r,kl.dirname(e)),n=await vi.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([vi.realpath(t),vi.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":nS.O_RDONLY|nS.O_NOFOLLOW|nS.O_NONBLOCK,c=await vi.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(),vi.lstat(e),vi.realpath(e)]);if(await p$(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Dv(n,l)||!Dv(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,h=Buffer.allocUnsafe(16*1024);for(;;){let w=await c.read(h,0,h.length,null);if(w.bytesRead===0)break;p+=w.bytesRead,f.push(Buffer.from(h.subarray(0,w.bytesRead)))}let[m,v,g]=await Promise.all([c.stat(),vi.lstat(e),vi.realpath(e)]);if(await p$(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!Dv(l,m)||!Dv(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Hv(e,t,r){let i=k6(r),n=Q(e,t),a=m$(e,t,i),o=B(e,a);await T(o,a);let s=Gn(await S6(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}async function v$(e){let t=Gn(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let r=h$(t.receiptHash),i=m$(e.paths,e.name,t.receiptHash),n=B(e.paths,i);await T(n,i);try{let o=await Hv(e.paths,e.name,r);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return r}catch(o){if(o.code!=="ENOENT")throw o}await ve(i,t,{containedRoot:n});let a=await Hv(e.paths,e.name,r);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return r}hi();Fe();Bn();var Rf=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Ba();el();Wn();var Nue=64*1024;var bue=3600*1e3;var kue=R6(E6);async function g$(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([Un(e,t.name,t.implementation_scope),aa({changeDir:pe(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:Km(r.scope.declaredArtifacts)},acceptanceIds:i.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${n}`,implementationExecutionId:n,scope:r}}var P6=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function aS(e,t){let r=[];for(let i of P6){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 x6(e,t){return aS(e,t).ok}async function w$(e){let t=await g$(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=gI({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:fs({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 bb({paths:e.paths,name:e.state.name,receipt:n});return{receipt:n,ref:a}}function C6(e){let{receipt:t,checkReceipt:r,context:i}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!x6(t,i.bindings)||r.status!=="passed"||r.stale)return!1;let n=fs({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 y$(e){let t=await kb(e.paths,e.state.name);if(t.length===0)return null;let r=[];for(let a of t)try{let o=await ms(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 g$(e.paths,e.state),!(await j6({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 oS({paths:e.paths,state:e.state,receipt:o});if(s===null||!C6({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 _6(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 A6=20;function I6(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<A6&&r.push({path:d,kind:l?u?"modified":"removed":"added"}))}return{changedPaths:r,changedPathCount:i,changedPathsTruncated:r.length!==i}}async function j6(e){let t=_6(e.context.scope.baseline),r=await Sc(e.paths,t,{origin:"explicit",now:e.now}),i=Kc({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=I6(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 oS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Hv(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}el();var wo=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 T6(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 $6(e){let t=T6(e.bundle.baseline),r=await Sc(e.paths,t,{origin:"explicit",now:e.now});return Kc({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 b$(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Un(e.paths,e.state.name,e.state.implementation_scope),r=await aa({changeDir:pe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await $6({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 k$(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await b$(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 O6(e){let t=await z({root:pe(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:cC(t.text)}}function D6(e){let{receipt:t,implementationScope:r}=e,i=[],n=fs({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 H6(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:Km(e.implementationScope.scope.declaredArtifacts)}}async function N$(e){let t=await ms(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=aS(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 wo([{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 oS({paths:e.paths,state:e.state,receipt:t});if(n){let a=D6({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 F6(e){let t=H6({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await N$({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof wo)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 N$({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof wo)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 wo(r)}function sS(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Fv(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:sS(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([b$(e),vs(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:sS(e.state.verification_result,"stale"),envelope:null};let i=await O6({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 F6({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:sS(e.state.verification_result,"invalid"),envelope:null}}}function L6(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function E$(e){try{return await q6.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function M6(e,t){try{return(await z({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function B6(e,t,r){let i=Ja(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=S$.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await M6(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await z({root:pe(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function V6(e,t){return E$(Yt(e,t))}async function qv(e){let t=e.now??new Date,r=await Me(e.paths,e.name),i=await Gt(e.paths,e.name),n=await te(e.paths.projectRoot),a=L6(r.name,t),o=S$.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(h=>B6(e.paths,r.name,h))),Fv({paths:e.paths,state:r,now:t}),Pv(e.paths,r.name),Tc(e.paths,r.name),$c(e.paths,r.name),V6(e.paths,r.name),E$(o)]);return RT({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]})}ci();cr();import{promises as cS}from"node:fs";import oa from"node:path";var W6="comet.native.archive-tree.v1",z6={maxDepth:128,maxEntries:2e4};function x$(e){let t={...z6,...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 R$(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 P$(e,t,r,i){if(r.entryCount+=1,r.entryCount>i.maxEntries)throw new Error(`Native Archive content exceeds ${i.maxEntries} entries`);e.push(t)}async function C$(e,t,r,i,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await Er({root:e,directory:t,label:`Native Archive content directory ${oa.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=R$(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=oa.join(t,u.name),f=oa.relative(e,d).replaceAll("\\","/"),p=await cS.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()){P$(r,{ref:f,kind:"directory"},i,n),await C$(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 h=await Qo({root:e,file:d,label:`Native Archive content file ${f}`});P$(r,{ref:f,kind:"file",hash:h.hash,size:h.size},i,n),await o.verify()}await o.verify();let l=await Er({root:e,directory:t,label:`Native Archive content directory ${oa.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(R$(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${oa.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function _$(e,t={}){let r=x$(t);e=oa.resolve(e);let i=await cS.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await C$(e,e,n,{entryCount:0},r,0);let o=JSON.stringify(n);return ae(`${W6}\0${o}`)}async function Wi(e,t={}){let r=x$(t);e=oa.resolve(e);let i;try{i=await cS.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 Qo({root:oa.dirname(e),file:e,label:`Native Archive transaction file ${oa.basename(e)}`})).hash};if(i.isDirectory())return{kind:"directory",hash:await _$(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}Oe();ei();import{promises as wr}from"node:fs";import Pt from"node:path";Z();cr();es();var Pf="comet.native.archive-cas.v1";function J6(e,t){let r="runtime/",i=t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(r.length):t,o=Pt.resolve(n,...a.split("/"));if(!q(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Mt(e,t){let r=J6(e,t);return T(B(e,r),r)}function yo(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function Sl(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function _r(e){let t=await Wi(e.target);if(!yo(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Sl(t)}`);return t}async function uS(e,t){let r=await an(e,t),i=await ht({root:e.runtimeDir,file:r.journal,maxBytes:null,label:`Native Archive transaction journal ${t}`}),n=Kh(JSON.parse(i.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Lv(e,t,r){let i=Kh({...t,status:r}),n=await an(e,i.id);return await ve(n.journal,i,{containedRoot:e.runtimeDir}),i}function Mv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function A$(e){return{...Mv(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function No(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function G6(e,t){return No(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ve(e){try{return await wr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function yn(e){let t=await wr.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=A$(t),i=await ht({root:B(e.paths,e.file),file:e.file,maxBytes:null,label:e.label}),n=await wr.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!G6(r,A$(n))||i.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Mv(n),size:i.size}}function K6(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!==Pf||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:Pf,operationId:t.id,role:r,hash:i,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Nn(e,t,r,i){let n=await an(e,t.id),a=Pt.join(n.backups,".cas"),o=`.${Pt.basename(i)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:a,originalRecord:Pt.join(a,`${r.id}.original.json`),postRecord:Pt.join(a,`${r.id}.post.json`),candidate:Pt.join(a,`${r.id}.candidate`),originalQuarantine:Pt.join(Pt.dirname(i),`${o}.original`),rollbackQuarantine:Pt.join(Pt.dirname(i),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(B(e,c),c))),s}async function gi(e){if(!await Ve(e.file))return null;let t=await ht({root:e.paths.runtimeDir,file:e.file,maxBytes:null,label:`Archive CAS ${e.operation.id} ${e.role} record`});return K6(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Bv(e){let t=await gi(e);if(t){if(!No(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await nn({root:e.paths.runtimeDir,directory:Pt.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Pf,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ve(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let i=await gi(e);if(!i||!No(i.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return i}async function bt(e){let t=await yn({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!No(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function U6(e){let t=await yn({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await Bv({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await bt({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function Y6(e){if(!await Ve(e.quarantine)||await Ve(e.target))return;let t=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await wr.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[r,i]=await Promise.all([wr.lstat(e.quarantine),wr.lstat(e.target)]);if(!No(Mv(r),Mv(i)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await wr.unlink(e.quarantine),await t.verify()}async function $$(e){if(await Ve(e.quarantine)){await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await bt({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 bt({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await wr.rename(e.target,e.quarantine),await t.verify(),await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await Y6(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 Is(e){if(!await Ve(e.file))return;await bt(e);let t=await qr({root:B(e.paths,e.file),directory:Pt.dirname(e.file),label:e.label});await t.verify(),await bt(e),await wr.unlink(e.file),await t.verify()}async function I$(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let i=await Mt(e,t.target),n=await Mt(e,t.backup),a=await Wi(n);if(a!==null){if(!yo(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await _r({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ha({sourceRoot:B(e,i),source:i,targetRoot:B(e,n),target:n,maxBytes:null,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await _r({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function O$(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 Nn(e.paths,e.journal,e.operation,e.target),i=await gi({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await Ve(r.originalQuarantine)){if(!i)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await bt({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:i,label:`Archive apply quarantine ${e.operation.target}`}),await I$(e.paths,e.operation,e.hooks),{record:i,quarantine:r.originalQuarantine}}if(!await Ve(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return i??=await U6({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await bt({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive apply target ${e.operation.target}`}),await I$(e.paths,e.operation,e.hooks),await $$({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 j$(e){let t=await Nn(e.paths,e.journal,e.operation,e.target);return await Ve(t.candidate)?(await yn({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await nn({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ha({sourceRoot:B(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:null,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 X6(e){let t=e.operation.stagedHash,r=await Nn(e.paths,e.journal,e.operation,e.target),i=await gi({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(i&&await Ve(e.target))return await bt({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive write target ${e.operation.target}`}),await Ve(r.candidate)&&await Is({paths:e.paths,file:r.candidate,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i;if(await Ve(e.target)){let c=await j$(e),l=await yn({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await yn({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!No(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return i=await Bv({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Is({paths:e.paths,file:c,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}let n=await j$(e),a=await yn({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await nn({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await bt({paths:e.paths,file:n,operation:e.operation,record:{schema:Pf,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await wr.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 yn({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!No(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return i=await Bv({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Is({paths:e.paths,file:n,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}async function Q6(e,t,r,i){let n=await Mt(e,r.target),a=await Mt(e,r.staged);if(await _r({target:a,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let o=await Nn(e,t,r,n);(!await gi({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await Ve(n))&&await O$({paths:e,journal:t,operation:r,target:n,hooks:i})}else{let o=await Wi(n);if(o!==null&&!yo(o,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${Sl(o)}`)}await X6({paths:e,journal:t,operation:r,staged:a,target:n,hooks:i}),await _r({target:n,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function Z6(e,t,r,i){let n=await Mt(e,r.target);await O$({paths:e,journal:t,operation:r,target:n,hooks:i}),await _r({target:n,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function eY(e,t){let r=await Mt(e,t.source),i=await Mt(e,t.target),[n,a]=await Promise.all([Wi(r),Wi(i)]);if(!(n===null&&yo(a,t.expectedSourceHash,"directory"))){if(!yo(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Sl(n)}, target=${Sl(a)}`);await wr.mkdir(Pt.dirname(i),{recursive:!0}),await wr.rename(r,i),await _r({target:i,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function tY(e,t,r,i){return r.type==="write"?Q6(e,t,r,i):r.type==="remove"?Z6(e,t,r,i):eY(e,r)}function rY(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 iY(e,t,r,i){let n=await Mt(e,r.target);if(r.type==="write"){let a=await Mt(e,r.staged);await _r({target:a,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let o=await Nn(e,t,r,n),s=await gi({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 bt({paths:e,file:n,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await _r({target:await Mt(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await gi({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 Ve(o.originalQuarantine))await bt({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 _r({target:n,expectedHash:null,label:`Completed Archive target ${r.target}`}),await _r({target:await Mt(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let a=await Nn(e,t,r,n),o=await gi({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 Ve(a.originalQuarantine))await bt({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 _r({target:await Mt(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await _r({target:n,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function D$(e,t,r){let i=t.status==="prepared"?await Lv(e,t,"applying"):t;if(i.status!=="applying")throw new Error(`Native Archive transaction ${i.id} cannot apply from ${i.status}`);let n=await qa(e,i.id),a=rY({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 iY(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 oi(e,i.id,"operation-started",l.id),await tY(e,i,l,r),await oi(e,i.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return i=await uS(e,i.id),i}async function nY(e){try{return await bt(e),!0}catch{return!1}}async function aY(e){await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await wr.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 bt({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function lS(e){if(e.operation.type!=="write")return;let t=await Nn(e.paths,e.journal,e.operation,e.target);if(!await Ve(t.candidate))return;let r=await yn({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Is({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Pf,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function oY(e,t,r,i){let n=await Mt(e,r.target),a=await Nn(e,t,r,n),o=r.expectedTargetHash,s=o===null?null:await gi({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:o}),c=r.type==="write"?await gi({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await Ve(a.candidate)&&await Ve(n)){let l=await yn({paths:e,file:a.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await yn({paths:e,file:n,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});No(l.identity,u.identity)&&(c=await Bv({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await Ve(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await bt({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await Ve(n)&&!(s!==null&&await nY({paths:e,file:n,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await Wi(n);if(yo(u,o)){await lS({paths:e,journal:t,operation:r,target:n});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await $$({paths:e,operation:r,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:i})}if(o===null){if(await Ve(n))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await Ve(n)){if(!s||!await Ve(a.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await aY({paths:e,operation:r,target:n,quarantine:a.originalQuarantine,record:s,hooks:i})}s&&await Ve(a.originalQuarantine)&&await Is({paths:e,file:a.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await Ve(a.rollbackQuarantine)&&await Is({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await lS({paths:e,journal:t,operation:r,target:n}),await _r({target:n,expectedHash:o,label:`Archive rollback target ${r.target}`})}async function sY(e,t){let r=await Mt(e,t.source),i=await Mt(e,t.target),[n,a]=await Promise.all([Wi(r),Wi(i)]);if(!(yo(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!yo(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Sl(n)}, target=${Sl(a)}`);await wr.mkdir(Pt.dirname(r),{recursive:!0}),await wr.rename(i,r)}}async function H$(e,t,r){let i=await qa(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 Lv(e,t,"rolling-back");await oi(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 sY(e,o):await oY(e,n,o,r));return await oi(e,n.id,"rollback-completed"),n=await Lv(e,n,"rolled-back"),n}async function T$(e,t,r){let i=await Mt(e,r.target);if(r.type==="write"){let n=await Nn(e,t,r,i),a=await gi({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 bt({paths:e,file:i,operation:r,record:a,label:`Archive commit target ${r.target}`});return}await _r({target:i,expectedHash:null,label:`Archive commit target ${r.target}`})}async function cY(e,t){for(let r of t.operations){if(r.type==="move")continue;let i=await Mt(e,r.target),n=await Nn(e,t,r,i);if(await Ve(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await T$(e,t,r),r.expectedTargetHash!==null){let a=await gi({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 Ve(n.originalQuarantine)&&await Is({paths:e,file:n.originalQuarantine,operation:r,record:a,label:`Archive commit original quarantine ${r.target}`})}await lS({paths:e,journal:t,operation:r,target:i})}for(let r of t.operations)r.type!=="move"&&await T$(e,t,r)}async function Vv(e,t,r){return r==="commit"&&await cY(e,t),await oi(e,t.id,r),r==="commit"?Lv(e,t,"committed"):t}Oe();To();hi();var hde=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});ci();zo();Fe();Z();cr();es();var Wv=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"},xf=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 q$(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 El.resolve(e.nativeRoot,...r.target.split("/"))}async function L$(e,t,r){let i=await qa(e,t.id);if(i.some(v=>v.type==="archive-finalized"))return;let n=i.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(w=>w.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await Wi(q$(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=q$(e,t),o=El.join(a,ct),s=await B_(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=Q(e,s.name),l=await At(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 v=bT(vn,l,new Set,qk,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=kT(vn,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},qk,void 0)}let d=ae(`archive:${t.id}:${s.name}`),f=await dr(c,u.trajectoryRef),p=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let h=p.find(v=>v.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(h&&t.schema==="comet.native.transaction.v2"&&(!lY(h.data,m)||h.runId!==u.runId||h.timestamp!==t.createdAt||h!==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 Vv(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await gc(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await M_(o,v)}h||(h=await ho({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await As({changeDir:c,run:u,trajectoryOffset:h.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await rs(c,u),await ff(e,s.name),t.schema==="comet.native.transaction.v2"?await Vv(e,t,"archive-finalized"):await gc(e,t,"archive-finalized")}async function dS(e,t){let r=je(e,t);try{let i=await F$.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${r}`);return await T(e.runtimeDir,r),await F$.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 uY(e,t,r){if(t.schema==="comet.native.transaction.v2"){if(!(await qa(e,t.id)).some(c=>c.type==="operation-started")){let c=await qv({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new xf(c,"Native Archive facts changed before the first transaction operation")}let o=await D$(e,t,{...r,beforeArchiveChangeMove:async c=>{await r?.beforeArchiveChangeMove?.(c);let l=await Me(e,t.change),u=await Fv({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 L$(e,o,r);let s=await Vv(e,o,"commit");return{journal:s,runtimeCleanupWarning:await dS(e,s.change)}}let i=await $C(e,t);await L$(e,i,r);let n=await gc(e,i,"commit");return{journal:n,runtimeCleanupWarning:n.change?await dS(e,n.change):null}}function dY(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(El.resolve(t.projectRoot)!==El.resolve(e.projectRoot)||El.resolve(t.nativeRoot)!==El.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function M$(e){return A(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await An(e.paths,"archive",`recover archive ${e.transactionId}`);try{let r=await Rr(e.paths,e.transactionId),i=r.schema==="comet.native.transaction.v2"?await uS(e.paths,e.transactionId):r;return dY(e.paths,i),i.status==="committed"?(i.change&&await dS(e.paths,i.change),i):i.status==="rolled-back"?i:e.strategy==="continue"?(await uY(e.paths,i)).journal:i.schema==="comet.native.transaction.v2"?H$(e.paths,i):Yh(e.paths,i)}finally{await In(t)}},{allowedTransactionId:e.transactionId})}Z();ot();function he(e,t,r){return e==="zh-CN"?r:t}var fS={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function B$(e,t){return typeof e=="string"&&fS[e]?he(t,fS[e].en,fS[e].zh):typeof e=="string"?e:""}function pS(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 fY(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 V$(e,t){let r=[];e.failed>0&&r.push(he(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(he(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(he(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=he(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function W$(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 hS(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function pY(e,t,r){return e==="done"?he(r,"complete","已完成"):e==="await-user"?he(r,"waiting for a user decision","等待用户决定"):e==="blocked"?he(r,"paused: needs attention","已暂停,需要处理"):t?he(r,"waiting for a user decision","等待用户决定"):he(r,"ready to continue","可继续推进")}function hY(e,t,r){let i=hS(e),n=[];r&&n.push(r);let a=he(i,`Change ${e.change}`,`需求 ${e.change}`),o=B$(e.phase,i),s=pY(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(V$(t,i));let c=e.userCommunication,l=z$(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function z$(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:he(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:he(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:he(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function mY(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function vY(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=B$(e.phase,t),n=e.status==="await-user"?he(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?he(t,"paused","已暂停"):e.status==="done"?he(t,"complete","已完成"):he(t,"in progress","进行中"),a=pS(e.acceptance)?`${he(t,", ",",")}${V$(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function gY(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 wY(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 yY(e){if(e.healthy){let i=e.repaired?he("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):he("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=NY(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:he("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:he("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function NY(e){return W$(e)?z$(e,hS(e)):void 0}function J$(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(wY(t))return yY(t);if(mY(t)){let i=gY(t.items);return{summary:[t.total===t.items.length?he(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):he(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>vY(a,i))].join(`
|
|
326
|
-
`)}}let r=t.continuation;if(W$(r)){let i=hS(r),n=
|
|
323
|
+
`)}import{promises as F$}from"fs";import El from"path";import{isDeepStrictEqual as uY}from"util";import{createHash as QK}from"crypto";function wT(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 yT(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))yT(e[t]);return Object.freeze(e)}function po(e){return yT(structuredClone(e))}function _k(e,t,r,i){return e.resolveStep({pkg:po(t),state:po(r),context:po(i)})}function NT(e,t,r,i,n,a){return e.resolveNext({pkg:po(t),state:po(r),step:po(i),outcome:po(n),context:po(a)})}function ZK(e,t,r){return QK("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function Ak(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function bT(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=_k(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=Ak(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:ZK(s.runId,s.iteration,o.id),stepId:o.id};return eU(e,s,c,r)}function eU(e,t,r,i){let n=wT(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 kT(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"?_k(i,e,t,n):void 0,o=a?Ak(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"?NT(i,e,t,o,r,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!Ak(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as L6}from"node:fs";import S$ from"node:path";Qe();import ST from"node:path";var tU="comet.native.archive-preflight.v1",rU="comet.native.archive-preflight.v1",iU="comet.native.archive-operation.v1",nU=/^[a-f0-9]{64}$/u,ET=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aU=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Rv(e,t){return e<t?-1:e>t?1:0}function oU(e,t){if(typeof e!="string"||!nU.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ia(e,t){return e===null?null:oU(e,t)}function sU(e,t){let r=ST.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||ST.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 cU(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function lU(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 uU(e,t){if(!ET.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=ia(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=ia(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=ia(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 dU(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:ia(e.contractHash,"Native archive contract hash"),acceptanceHash:ia(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:ia(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:ia(e.reportHash,"Native archive report hash"),envelopeHash:ia(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:ia(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 fU(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!aU.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(Rv);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function pU(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(Rv)}function RT(e){if(!ET.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(uU).sort((l,u)=>Rv(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:j(iU,l)})),i=dU(e.evidence),n=lU(e.workspace),a=[...new Set([...fU(e.findingCodes??[]),...pU({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(Rv),o=cU(e.revision),s=sU(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:tU,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:j(rU,c)}}Ht();Qe();import{createHash as hU}from"node:crypto";import PT from"node:path";var mU="comet.native.conflict-radar.v1",Cr=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}),vU="comet.native.conflict-radar.v1",gU="comet.native.conflict-radar-signals.v1",wU=/^[a-f0-9]{64}$/u,_T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yU=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),NU=new Set(["capability","operation","baseHash"]),bU=new Set(["path","kind"]);function gl(e,t){return e<t?-1:e>t?1:0}function Ik(e){return Buffer.byteLength(e,"utf8")}function jk(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 Tk(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(Ik(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function kU(e,t){let r=Tk(e,t,Cr.maxArtifactPathBytes),i=PT.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)||PT.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 AT(e,t){if(typeof e!="string"||!wU.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function SU(e,t){let r=jk(e,NU,t),i=Tk(r.capability,`${t} capability`,Cr.maxCapabilityBytes);if(!_T.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:AT(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 EU(e,t){let r=jk(e,bU,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:kU(r.path,`${t} path`),kind:r.kind}}function RU(e,t){let r=jk(e,yU,`Conflict radar change ${t}`),i=Tk(r.name,`Conflict radar change ${t} name`,Cr.maxNameBytes);if(!_T.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>Cr.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>Cr.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>SU(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>gl(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)=>EU(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>gl(c.path,l.path)||gl(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:AT(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function PU(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Cr.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(RU).sort((n,a)=>gl(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)>Cr.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Cr.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function xU(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 CU(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 _U(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function AU(e,t){let r=[],i=hU("sha256").update(`${gU}
|
|
324
|
+
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Lu(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Cr.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(xU(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=CU(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:_U(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function xT(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function IU(e,t){return xT(e.classification)-xT(t.classification)||gl(e.left,t.left)||gl(e.right,t.right)}function CT(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:mU,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 IT(e){let t=PU(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(AU(t[s],t[c]));r.sort(IU);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=j(vU,{changes:t,relationships:i}),a=r.slice(0,Cr.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=CT(t,r,a,n);for(;a.length>0&&Ik(JSON.stringify(o))>Cr.maxSerializedBytes;)a=a.slice(0,-1),o=CT(t,r,a,n);if(Ik(JSON.stringify(o))>Cr.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}hi();cr();var jU=4096;async function TU(e,t=Cr.maxChanges){try{let r=await Er({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 jT(e,t){let r=await Me(e,t),[i,n]=await Promise.all([r.implementation_scope?rl(e,t,r.implementation_scope):null,Gt(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 Pv(e,t,r={}){let n=(await TU(e,jU)).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 jT(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await jT(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=IT([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"]:[]]}}ot();Z();import{promises as YU}from"fs";import XU from"path";import{isDeepStrictEqual as _v}from"util";Oe();ci();zo();Fe();Z();cr();Bn();Qe();Qe();var wl={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var $U=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function OU(e,t){return e<t?-1:e>t?1:0}function DU(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"||!$U.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(OU)}function $k(e=[]){return DU(e,"Native repair failed check IDs",wl.maxFailedCheckIds,!0)}function TT(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function HU(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:TT(e.failedAcceptanceIds,t.failedAcceptanceIds)&&TT(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Ok(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(HU(i,a))break;r+=1,i=a}return r}Md();Wn();function xv(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 $T="repairStagnation",Xr={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},qU=/^[a-f0-9]{64}$/u;var LU=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),MU=["data","runId","sequence","timestamp","type"],OT=["disposition","overrideSummaryHash","signatureHash"],BU=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],DT=12;function Hk(e,t){return e<t?-1:e>t?1:0}function HT(e,t,r){let i=Object.keys(e).sort(Hk);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function Cv(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 yf(e,t){if(typeof e!="string"||!qU.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function VU(e){if(!Array.isArray(e)||e.length>wl.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(Hk)}function FT(e){if(typeof e!="string"||e.length===0||e.length>Xr.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 Dk(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>Xr.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Xr.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>Xr.maxTextCharacters&&(!n||e.length>Xr.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>Xr.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>Xr.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Dk(s,t+1,r,`${i}[${c}]`));return}let a=Cv(e,i),o=Object.keys(a);if(o.length>Xr.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>Xr.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>Xr.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Dk(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function WU(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 zU(e,t,r){let i=Cv(e,`Native repair trajectory event ${t+1}`);if(HT(i,MU,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(WU(i.timestamp),typeof i.type!="string"||!LU.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(FT(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 Dk(i.data,0,n,"Native trajectory event data"),Cv(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Fk(e){let t=Cv(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Hk),i=r.length===OT.length&&r.every((l,u)=>l===OT[u]);i||HT(t,BU,"Native repair trajectory projection");let n=yf(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:yf(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=yf(t.contractHash,"Native repair trajectory contract hash"),s=VU(t.failedAcceptanceIds),c=$k(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 JU(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 GU(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??DT;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Ok({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<wl.warningAtConsecutiveFailures?"continue":a<wl.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function KU(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??DT;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 qT(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Xr.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=FT(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=zU(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Xr.maxTotalDataNodes||c>Xr.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,p=Object.hasOwn(f,"repairScopeHash")?yf(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?yf(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,$T)){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 h=Fk(f[$T]);if(JU(f,h),h.overrideSummaryHash===null)h.contractHash!==null&&a!==null&&h.contractHash!==a&&(r.length=0,o=0),h.contractHash!==null&&(a=h.contractHash),h.contractHash===null&&p!==null&&n!==null&&p!==n&&(r.length=0,o=0),p!==null&&(n=p),GU(h,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:h.signatureHash,...h.contractHash===null?{}:{failedAcceptanceIds:[...h.failedAcceptanceIds],failedCheckIds:[...h.failedCheckIds]}});else{if(i?.contractHash===null&&p!==null&&n!==null&&p!==n)throw new Error("Native repair override cannot cross implementation scope progress");KU(h,r,i);let m=r.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:h.signatureHash,summaryHash:h.overrideSummaryHash})}if(i=h,r.length>wl.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function LT(e){return qT(e).history}function MT(e){let t=qT(e).latestProjection;return t?{...t}:null}ci();var vn={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:[]},Nf=ae("comet-native-runtime:v3:scope-reopen"),UU=[{skillVersion:"3",skillHash:ae("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ae("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ae("comet-native-runtime:v1")}];function BT(e){return e.skillVersion===vn.definition.metadata.version&&e.skillHash===Nf||UU.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var qk={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}};ci();async function ho(e){let r={sequence:(await dr(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 E_(e.changeDir,e.run.trajectoryRef,r),r}async function As(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:ae(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await R_(e.changeDir,e.run.checkpointRef,t),t}ci();function VT(e){return ae(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}))}cc();var XT=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],QU=new Set(XT),QT=new Set([...XT,"minimum_runtime_version","revision"]),ZU=new Set([...QT,"operation"]),Lk=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),e6=new Set([...Lk,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),bf=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 Yt(e,t){return XU.join(Q(e,t),"transition.json")}function t6(e){return`transition-${e}`}async function r6(e,t,r){let i=t6(t);return An(e,i,r)}async function wn(e,t,r,i){let n=await r6(e,t,r);try{return await i()}finally{await In(n)}}function Iv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Bk(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 Av(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function gn(e,t){return _v(e,t)}function Mk(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=>!e6.has(u)),a=[...Lk].find(u=>!Object.hasOwn(r,u)),o=Lk.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(xv(r.summary,"Native transition journal event summary"),Rt(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&&(xv(r.noCodeReason,"Native transition journal event no-code reason"),Rt(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")?Fk(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 i6(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 Mk({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Mk(e,t)}function Vk(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?i6(e.eventData,e.evidenceHash):Mk(e.eventData,e.evidenceHash),n=Wa(e.nextRun),a=e.previousRun===null?null:Wa(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function WT(e,t,r=!1){if(e.skill!==vn.definition.metadata.name||(r?!BT(e):e.skillVersion!==vn.definition.metadata.version||e.skillHash!==Nf)||e.orchestration!==vn.definition.orchestration.mode||e.pendingRef!==Lr.pendingRef||e.trajectoryRef!==Lr.trajectoryRef||e.contextRef!==Lr.contextRef||e.artifactsRef!==Lr.artifactsRef||e.checkpointRef!==Lr.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function zT(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 JT(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 Wk(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(WT(o,"next Run",i||a!==null),JT(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(WT(a,"previous Run",!0),JT(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(!_v(zT(a),zT(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function n6(e,t,r){return ae(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function ZT(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function GT(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function zk(e,t,r,i,n=!1){let a=r.eventData,o=GT(e),s=GT(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&&_v(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&&_v(e.spec_changes,t.spec_changes),l=VT({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=n6(e.name,a.summary,t.spec_changes),l=ae(`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 Jk(e,t){let r=Iv(e);if(Bk(r,ZU),r.schema!==ja)throw new Error(`Expected Native transition schema ${ja}`);let i=Av(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 ${ja} minimum_runtime_version must be ${3}`);let n=Av(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=Vk(r,t),o=zt(r.previousState),s=zt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(zk(o,s,a,r.operation),Wk(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:ja,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 a6(e,t){let r=Iv(e);if(Bk(r,QU),r.schema!==Jo)throw new Error(`Expected Native transition schema ${Jo}`);let i=Vk(r,t,!0),n=Ta(r.previousState),a=Ta(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return zk(n,a,i,ZT(n,a,i.eventData),!0),Wk(n,a,i,!0),{schema:Jo,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 Gk(e,t){let r=Iv(e);if(Bk(r,QT),r.schema!==jn)throw new Error(`Expected Native transition schema ${jn}`);if(Av(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${jn} minimum_runtime_version must be 2`);let n=Av(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Vk(r,t,!0),o=Ii(r.previousState),s=Ii(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(zk(o,s,a,ZT(o,s,a.eventData),!0),Wk(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:jn,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 o6(e,t){let r=Iv(e);if(r.schema===ja)return{status:"current",journal:Jk(r,t)};if(r.schema===Jo)return{status:"migration-required",journal:a6(r,t)};if(r.schema===jn)return{status:"migration-required",journal:Gk(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function Kk(e,t){let r=Yt(e,t),i=B(e,r);await T(i,r);try{let n=await ht({root:i,file:r,maxBytes:null,label:`Native transition journal ${t}`});return o6(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function na(e,t){let r=await Kk(e,t);if(!r)return null;if(r.status==="migration-required")throw new bf(t);return r.journal}function KT(e,t){if(gn(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(gn(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function UT(e,t){if(gn(e,t.nextState))return"next";if(gn(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function s6(e){let{journal:t}=e;return e$({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 e$(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function YT(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=s6({sequence:a.index+1,journal:t,type:a.event.type});if(!gn(e$(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 yl(e,t,r){if(await Tc(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await hm(e,t);let i=await na(e,t);if(!i)return null;let n=Q(e,t),a=YT(await dr(n,i.nextRun.trajectoryRef),i),[o,s]=await Promise.all([At(n),Me(e,t)]),c=KT(o,i),l=UT(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 rs(n,i.nextRun),await r?.afterRunStateWritten?.(i)),!gn(await At(n),i.nextRun))throw new Error(`Native transition Run content changed while continuing ${i.change}; recovery journal was preserved`);if(l==="previous"){let v=await ld(e,i.nextState,i.previousState.revision);if(!gn(v,i.nextState))throw new Error(`Native transition change write diverged for ${i.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(i)}if(!gn(await Me(e,t),i.nextState))throw new Error(`Native transition change content changed while continuing ${i.change}; recovery journal was preserved`);let u=await na(e,t);if(!u||!gn(u,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was preserved`);let d=YT(await dr(n,i.nextRun.trajectoryRef),i);i.previousRun===null&&(d.started||await ho({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 ho({changeDir:n,run:i.nextRun,type:"state_transitioned",data:{...i.eventData,transitionId:i.id},now:new Date(i.createdAt)})),await As({changeDir:n,run:i.nextRun,trajectoryOffset:f.sequence,evidenceHash:i.evidenceHash,now:new Date(i.createdAt)});let[p,h]=await Promise.all([At(n),Me(e,t)]);KT(p,{...i,previousRun:i.nextRun}),UT(h,{...i,previousState:i.nextState});let m=await na(e,t);if(!m||!gn(m,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was not removed`);return await YU.rm(Yt(e,t),{force:!0}),i.nextState}async function t$(e,t,r){return A(e,`continue transition ${t}`,()=>wn(e,t,`continue transition ${t}`,()=>yl(e,t,r)))}Vu();Ht();Ht();Vu();Qe();import r$ from"node:path";var c6="comet.native.contract.v1",l6="comet.native.acceptance-set.v1",i$=/^[a-f0-9]{64}$/u,kf={maxAcceptanceCriteria:Bu.maxCriteria};function n$(e,t){let r=r$.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})||r$.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 a$(e){return j("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
325
|
+
`))}function u6(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(i$))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(i$))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=n$(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:a$(e.markdown)},markdown:e.markdown}}function d6(e,t){return o$(e.id,t.id)}function o$(e,t){return e<t?-1:e>t?1:0}function s$(e){let t=n$(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(u6).sort((d,f)=>o$(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=Ah(e.briefMarkdown,t,kf.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...Ih(f,d.source,kf.maxAcceptanceCriteria-a.length)),a.push(...oC(f,d.source,kf.maxAcceptanceCriteria-a.length)));if(a.sort(d6),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>kf.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${kf.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:a$(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=j(l6,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:j(c6,u)}}var jv={maxSpecs:64};async function aa(e){if(e.specChanges.length>jv.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await z({root:e.changeDir,ref:e.briefRef,maxBytes:null}),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 z({root:e.changeDir,ref:n.source,maxBytes:null});r+=a.size,i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:s$({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}hi();Ba();Wn();Md();import{execFile as R6}from"node:child_process";Nh();eb();import{promisify as P6}from"node:util";import{promises as w6}from"fs";Oe();import Nl from"path";ci();Z();cr();Ll();Bn();var Sf={maxArtifacts:128},bl=/^[a-f0-9]{64}$/u;function Tv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $v(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 mo(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 c$(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Uk(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function f6(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Nl.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=Nl.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Yk(e,t){return Nl.join(Q(e,t),"checkpoints","progress.json")}function vo(e,t){return Nl.join(Q(e,t),"checkpoint-journal.json")}function Xk(e,t,r){if(!bl.test(r))throw new Error("Native checkpoint manifest hash is invalid");return Nl.join(Q(e,t),"checkpoints","manifests",`${r}.json`)}function p6(e){if(!bl.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Qk(e,t,r){let i=await ht({root:e,file:t,maxBytes:null,label:r});return JSON.parse(i.bytes.toString("utf8"))}function h6(e,t){let r=Tv(e,`checkpoint manifest artifact ${t}`);$v(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=f6(mo(r.path,`checkpoint artifact ${t} path`,4096)),n=Ki(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!bl.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Uk(r.size,`checkpoint artifact ${t} size`)}}function Ov(e,t){let r=Tv(e,"Native checkpoint manifest");if($v(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>Sf.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(h6),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=Uk(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function Zk(e){return ae(JSON.stringify(Ov(e,e.change)))}function eS(e,t){let r=Tv(e,"Native progress checkpoint");if($v(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=c$(r.previousRevision,"Native checkpoint previousRevision"),a=c$(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=mo(r.manifestHash,"Native checkpoint manifestHash",64);if(!bl.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=p6(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=mo(r.inputHash,"Native checkpoint inputHash",64);if(!bl.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=mo(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Uk(r.artifactCount,"Native checkpoint artifactCount");if(u>Sf.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=mo(r.summary,"Native checkpoint summary"),f=mo(r.nextAction,"Native checkpoint nextAction");if(Rt(d)!==d||Rt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:mo(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 m6(e,t){let r=Tv(e,"Native checkpoint journal");if($v(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=zt(r.previousState),n=zt(r.nextState),a=eS(r.checkpoint,t),o=Ov(r.manifest,t),s=mo(r.inputHash,"Native checkpoint journal inputHash",64),c=ae(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!bl.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!==Zk(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 v6(e,t,r){let i=Nl.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=Rg(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await Qo({root:e.projectRoot,file:i,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 g6(e,t){let r=Yk(e,t),i=B(e,r);await T(i,r);try{return eS(await Qk(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function tS(e,t,r){let i=Xk(e,t,r),n=B(e,i);await T(n,i);let a=await Qk(n,i,"Native checkpoint manifest"),o=Ov(a,t);if(rS(e,o),Zk(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function go(e,t){let r=vo(e,t),i=B(e,r);await T(i,r);try{let n=m6(await Qk(i,r,"Native checkpoint journal"),t);return rS(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function l$(e,t,r,i){let n=Ov(r,t);rS(e,n);let a=Zk(n),o=Xk(e,t,a),s=B(e,o);await T(s,o);try{let c=await tS(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 ve(o,n,{containedRoot:s,beforeCommit:i?.beforeCommit}),a}function rS(e,t){for(let r of t.artifacts){let i=Rg(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function u$(e,t){let r=eS(t,t.change),i=await tS(e,r.change,r.manifestHash),n=ae(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=Yk(e,t.change),o=B(e,a);await T(o,a),await ve(a,r,{containedRoot:o})}async function d$(e){let t;try{t=await g6(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:Yk(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 tS(e.paths,e.name,t.manifestHash);let a=ae(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 v6(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:Xk(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}Fe();async function iS(e,t,r){let i=await go(e,t);if(!i)return null;if(await l$(e,i.change,i.manifest)!==i.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await ld(e,i.nextState,i.previousState.revision,{allowPendingCheckpointRecovery:!0}),await r?.afterStateWritten?.(i),await u$(e,i.checkpoint),await r?.afterProgressWritten?.(i),await w6.rm(vo(e,t),{force:!0}),i}async function f$(e,t,r){return A(e,`continue checkpoint ${t}`,()=>wn(e,t,`continue checkpoint ${t}`,async()=>(await yl(e,t),iS(e,t,r))))}async function Ef(e,t){await yl(e,t),await iS(e,t)}Oe();Qc();Z();ei();import{constants as nS,promises as vi}from"node:fs";import kl from"node:path";var y6=/^[a-f0-9]{64}$/u,N6=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u;function b6(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Dv(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Tr(r,i)?ne(r,i):ne(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function k6(e,t){let r=kl.resolve(e),i=kl.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["",...kl.relative(r,i).split(kl.sep).filter(Boolean)]){o&&(a=kl.join(a,o));let s=await vi.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await vi.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 p$(e){for(let t of e){let r=await vi.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!b6(t,r)||await vi.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function h$(e){if(!y6.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function S6(e){let t=N6.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function m$(e,t,r){return Ia(Q(e,t),h$(r))}async function E6(e,t,r){let i=await k6(r,kl.dirname(e)),n=await vi.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");let[a,o]=await Promise.all([vi.realpath(t),vi.realpath(e)]);if(!q(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":nS.O_RDONLY|nS.O_NOFOLLOW|nS.O_NONBLOCK,c=await vi.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(),vi.lstat(e),vi.realpath(e)]);if(await p$(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Dv(n,l)||!Dv(l,u))throw new Error("Native check receipt changed while opening");let f=[],p=0,h=Buffer.allocUnsafe(16*1024);for(;;){let w=await c.read(h,0,h.length,null);if(w.bytesRead===0)break;p+=w.bytesRead,f.push(Buffer.from(h.subarray(0,w.bytesRead)))}let[m,v,g]=await Promise.all([c.stat(),vi.lstat(e),vi.realpath(e)]);if(await p$(i),!v.isFile()||v.isSymbolicLink()||g!==o||!q(a,g)||!Dv(l,m)||!Dv(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,p).toString("utf8"))}finally{await c.close()}}async function Hv(e,t,r){let i=S6(r),n=Q(e,t),a=m$(e,t,i),o=B(e,a);await T(o,a);let s=Gn(await E6(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}async function v$(e){let t=Gn(e.receipt);if(t.change!==e.name)throw new Error("Native check receipt change mismatch");let r=h$(t.receiptHash),i=m$(e.paths,e.name,t.receiptHash),n=B(e.paths,i);await T(n,i);try{let o=await Hv(e.paths,e.name,r);if(JSON.stringify(o)!==JSON.stringify(t))throw new Error(`Native check receipt hash collision for ${t.receiptHash}`);return r}catch(o){if(o.code!=="ENOENT")throw o}await ve(i,t,{containedRoot:n});let a=await Hv(e.paths,e.name,r);if(JSON.stringify(a)!==JSON.stringify(t))throw new Error("Native check receipt changed while being persisted");return r}hi();Fe();Bn();var Rf=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Ba();el();Wn();var bue=64*1024;var kue=3600*1e3;var Sue=P6(R6);async function g$(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([Un(e,t.name,t.implementation_scope),aa({changeDir:pe(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:Km(r.scope.declaredArtifacts)},acceptanceIds:i.contract.acceptance.map(a=>a.id).sort(),implementationAuthor:`native-implementation:${n}`,implementationExecutionId:n,scope:r}}var x6=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function aS(e,t){let r=[];for(let i of x6){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 C6(e,t){return aS(e,t).ok}async function w$(e){let t=await g$(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=gI({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:fs({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 bb({paths:e.paths,name:e.state.name,receipt:n});return{receipt:n,ref:a}}function _6(e){let{receipt:t,checkReceipt:r,context:i}=e;if(t.kind!=="static-inspection"||t.role!=="required-check"||t.status!=="passed"||!C6(t,i.bindings)||r.status!=="passed"||r.stale)return!1;let n=fs({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 y$(e){let t=await kb(e.paths,e.state.name);if(t.length===0)return null;let r=[];for(let a of t)try{let o=await ms(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 g$(e.paths,e.state),!(await T6({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 oS({paths:e.paths,state:e.state,receipt:o});if(s===null||!_6({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 A6(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 I6=20;function j6(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<I6&&r.push({path:d,kind:l?u?"modified":"removed":"added"}))}return{changedPaths:r,changedPathCount:i,changedPathsTruncated:r.length!==i}}async function T6(e){let t=A6(e.context.scope.baseline),r=await Sc(e.paths,t,{origin:"explicit",now:e.now}),i=Kc({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=j6(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 oS(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Hv(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}el();var wo=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 $6(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 O6(e){let t=$6(e.bundle.baseline),r=await Sc(e.paths,t,{origin:"explicit",now:e.now});return Kc({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 b$(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await Un(e.paths,e.state.name,e.state.implementation_scope),r=await aa({changeDir:pe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await O6({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 k$(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await b$(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 D6(e){let t=await z({root:pe(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:cC(t.text)}}function H6(e){let{receipt:t,implementationScope:r}=e,i=[],n=fs({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 F6(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:Km(e.implementationScope.scope.declaredArtifacts)}}async function N$(e){let t=await ms(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=aS(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 wo([{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 oS({paths:e.paths,state:e.state,receipt:t});if(n){let a=H6({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 q6(e){let t=F6({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await N$({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof wo)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 N$({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof wo)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 wo(r)}function sS(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function Fv(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:sS(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([b$(e),vs(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:sS(e.state.verification_result,"stale"),envelope:null};let i=await D6({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 q6({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:sS(e.state.verification_result,"invalid"),envelope:null}}}function M6(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function E$(e){try{return await L6.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function B6(e,t){try{return(await z({root:e,ref:t,maxBytes:null})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function V6(e,t,r){let i=Ja(e,r.capability);if(!q(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=S$.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await B6(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await z({root:pe(e,t),ref:r.source,maxBytes:null})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function W6(e,t){return E$(Yt(e,t))}async function qv(e){let t=e.now??new Date,r=await Me(e.paths,e.name),i=await Gt(e.paths,e.name),n=await te(e.paths.projectRoot),a=M6(r.name,t),o=S$.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(h=>V6(e.paths,r.name,h))),Fv({paths:e.paths,state:r,now:t}),Pv(e.paths,r.name),Tc(e.paths,r.name),$c(e.paths,r.name),W6(e.paths,r.name),E$(o)]);return RT({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]})}ci();cr();import{promises as cS}from"node:fs";import oa from"node:path";var z6="comet.native.archive-tree.v1",J6={maxDepth:128,maxEntries:2e4};function x$(e){let t={...J6,...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 R$(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 P$(e,t,r,i){if(r.entryCount+=1,r.entryCount>i.maxEntries)throw new Error(`Native Archive content exceeds ${i.maxEntries} entries`);e.push(t)}async function C$(e,t,r,i,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await Er({root:e,directory:t,label:`Native Archive content directory ${oa.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=R$(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=oa.join(t,u.name),f=oa.relative(e,d).replaceAll("\\","/"),p=await cS.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()){P$(r,{ref:f,kind:"directory"},i,n),await C$(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 h=await Qo({root:e,file:d,label:`Native Archive content file ${f}`});P$(r,{ref:f,kind:"file",hash:h.hash,size:h.size},i,n),await o.verify()}await o.verify();let l=await Er({root:e,directory:t,label:`Native Archive content directory ${oa.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(R$(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${oa.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function _$(e,t={}){let r=x$(t);e=oa.resolve(e);let i=await cS.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await C$(e,e,n,{entryCount:0},r,0);let o=JSON.stringify(n);return ae(`${z6}\0${o}`)}async function Wi(e,t={}){let r=x$(t);e=oa.resolve(e);let i;try{i=await cS.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 Qo({root:oa.dirname(e),file:e,label:`Native Archive transaction file ${oa.basename(e)}`})).hash};if(i.isDirectory())return{kind:"directory",hash:await _$(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}Oe();ei();import{promises as wr}from"node:fs";import Pt from"node:path";Z();cr();es();var Pf="comet.native.archive-cas.v1";function G6(e,t){let r="runtime/",i=t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(r.length):t,o=Pt.resolve(n,...a.split("/"));if(!q(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function Mt(e,t){let r=G6(e,t);return T(B(e,r),r)}function yo(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function Sl(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function _r(e){let t=await Wi(e.target);if(!yo(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Sl(t)}`);return t}async function uS(e,t){let r=await an(e,t),i=await ht({root:e.runtimeDir,file:r.journal,maxBytes:null,label:`Native Archive transaction journal ${t}`}),n=Kh(JSON.parse(i.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Lv(e,t,r){let i=Kh({...t,status:r}),n=await an(e,i.id);return await ve(n.journal,i,{containedRoot:e.runtimeDir}),i}function Mv(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function A$(e){return{...Mv(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function No(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function K6(e,t){return No(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Ve(e){try{return await wr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function yn(e){let t=await wr.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=A$(t),i=await ht({root:B(e.paths,e.file),file:e.file,maxBytes:null,label:e.label}),n=await wr.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!K6(r,A$(n))||i.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Mv(n),size:i.size}}function U6(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!==Pf||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:Pf,operationId:t.id,role:r,hash:i,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Nn(e,t,r,i){let n=await an(e,t.id),a=Pt.join(n.backups,".cas"),o=`.${Pt.basename(i)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:a,originalRecord:Pt.join(a,`${r.id}.original.json`),postRecord:Pt.join(a,`${r.id}.post.json`),candidate:Pt.join(a,`${r.id}.candidate`),originalQuarantine:Pt.join(Pt.dirname(i),`${o}.original`),rollbackQuarantine:Pt.join(Pt.dirname(i),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(B(e,c),c))),s}async function gi(e){if(!await Ve(e.file))return null;let t=await ht({root:e.paths.runtimeDir,file:e.file,maxBytes:null,label:`Archive CAS ${e.operation.id} ${e.role} record`});return U6(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Bv(e){let t=await gi(e);if(t){if(!No(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await nn({root:e.paths.runtimeDir,directory:Pt.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Pf,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ve(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let i=await gi(e);if(!i||!No(i.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return i}async function bt(e){let t=await yn({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!No(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function Y6(e){let t=await yn({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await Bv({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await bt({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function X6(e){if(!await Ve(e.quarantine)||await Ve(e.target))return;let t=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await wr.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[r,i]=await Promise.all([wr.lstat(e.quarantine),wr.lstat(e.target)]);if(!No(Mv(r),Mv(i)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await wr.unlink(e.quarantine),await t.verify()}async function $$(e){if(await Ve(e.quarantine)){await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await bt({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 bt({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await wr.rename(e.target,e.quarantine),await t.verify(),await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await X6(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 Is(e){if(!await Ve(e.file))return;await bt(e);let t=await qr({root:B(e.paths,e.file),directory:Pt.dirname(e.file),label:e.label});await t.verify(),await bt(e),await wr.unlink(e.file),await t.verify()}async function I$(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let i=await Mt(e,t.target),n=await Mt(e,t.backup),a=await Wi(n);if(a!==null){if(!yo(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await _r({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Ha({sourceRoot:B(e,i),source:i,targetRoot:B(e,n),target:n,maxBytes:null,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await _r({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function O$(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 Nn(e.paths,e.journal,e.operation,e.target),i=await gi({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await Ve(r.originalQuarantine)){if(!i)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await bt({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:i,label:`Archive apply quarantine ${e.operation.target}`}),await I$(e.paths,e.operation,e.hooks),{record:i,quarantine:r.originalQuarantine}}if(!await Ve(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return i??=await Y6({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await bt({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive apply target ${e.operation.target}`}),await I$(e.paths,e.operation,e.hooks),await $$({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 j$(e){let t=await Nn(e.paths,e.journal,e.operation,e.target);return await Ve(t.candidate)?(await yn({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await nn({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Ha({sourceRoot:B(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:null,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 Q6(e){let t=e.operation.stagedHash,r=await Nn(e.paths,e.journal,e.operation,e.target),i=await gi({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(i&&await Ve(e.target))return await bt({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive write target ${e.operation.target}`}),await Ve(r.candidate)&&await Is({paths:e.paths,file:r.candidate,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i;if(await Ve(e.target)){let c=await j$(e),l=await yn({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await yn({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!No(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return i=await Bv({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Is({paths:e.paths,file:c,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}let n=await j$(e),a=await yn({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await nn({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await bt({paths:e.paths,file:n,operation:e.operation,record:{schema:Pf,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await wr.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 yn({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!No(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return i=await Bv({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Is({paths:e.paths,file:n,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}async function Z6(e,t,r,i){let n=await Mt(e,r.target),a=await Mt(e,r.staged);if(await _r({target:a,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let o=await Nn(e,t,r,n);(!await gi({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await Ve(n))&&await O$({paths:e,journal:t,operation:r,target:n,hooks:i})}else{let o=await Wi(n);if(o!==null&&!yo(o,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${Sl(o)}`)}await Q6({paths:e,journal:t,operation:r,staged:a,target:n,hooks:i}),await _r({target:n,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function eY(e,t,r,i){let n=await Mt(e,r.target);await O$({paths:e,journal:t,operation:r,target:n,hooks:i}),await _r({target:n,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function tY(e,t){let r=await Mt(e,t.source),i=await Mt(e,t.target),[n,a]=await Promise.all([Wi(r),Wi(i)]);if(!(n===null&&yo(a,t.expectedSourceHash,"directory"))){if(!yo(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Sl(n)}, target=${Sl(a)}`);await wr.mkdir(Pt.dirname(i),{recursive:!0}),await wr.rename(r,i),await _r({target:i,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function rY(e,t,r,i){return r.type==="write"?Z6(e,t,r,i):r.type==="remove"?eY(e,t,r,i):tY(e,r)}function iY(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 nY(e,t,r,i){let n=await Mt(e,r.target);if(r.type==="write"){let a=await Mt(e,r.staged);await _r({target:a,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let o=await Nn(e,t,r,n),s=await gi({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 bt({paths:e,file:n,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await _r({target:await Mt(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await gi({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 Ve(o.originalQuarantine))await bt({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 _r({target:n,expectedHash:null,label:`Completed Archive target ${r.target}`}),await _r({target:await Mt(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let a=await Nn(e,t,r,n),o=await gi({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 Ve(a.originalQuarantine))await bt({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 _r({target:await Mt(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await _r({target:n,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function D$(e,t,r){let i=t.status==="prepared"?await Lv(e,t,"applying"):t;if(i.status!=="applying")throw new Error(`Native Archive transaction ${i.id} cannot apply from ${i.status}`);let n=await qa(e,i.id),a=iY({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 nY(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 oi(e,i.id,"operation-started",l.id),await rY(e,i,l,r),await oi(e,i.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return i=await uS(e,i.id),i}async function aY(e){try{return await bt(e),!0}catch{return!1}}async function oY(e){await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await qr({root:B(e.paths,e.target),directory:Pt.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await bt({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await wr.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 bt({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function lS(e){if(e.operation.type!=="write")return;let t=await Nn(e.paths,e.journal,e.operation,e.target);if(!await Ve(t.candidate))return;let r=await yn({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Is({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Pf,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function sY(e,t,r,i){let n=await Mt(e,r.target),a=await Nn(e,t,r,n),o=r.expectedTargetHash,s=o===null?null:await gi({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:o}),c=r.type==="write"?await gi({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await Ve(a.candidate)&&await Ve(n)){let l=await yn({paths:e,file:a.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await yn({paths:e,file:n,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});No(l.identity,u.identity)&&(c=await Bv({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await Ve(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await bt({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await Ve(n)&&!(s!==null&&await aY({paths:e,file:n,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await Wi(n);if(yo(u,o)){await lS({paths:e,journal:t,operation:r,target:n});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await $$({paths:e,operation:r,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:i})}if(o===null){if(await Ve(n))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await Ve(n)){if(!s||!await Ve(a.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await oY({paths:e,operation:r,target:n,quarantine:a.originalQuarantine,record:s,hooks:i})}s&&await Ve(a.originalQuarantine)&&await Is({paths:e,file:a.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await Ve(a.rollbackQuarantine)&&await Is({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await lS({paths:e,journal:t,operation:r,target:n}),await _r({target:n,expectedHash:o,label:`Archive rollback target ${r.target}`})}async function cY(e,t){let r=await Mt(e,t.source),i=await Mt(e,t.target),[n,a]=await Promise.all([Wi(r),Wi(i)]);if(!(yo(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!yo(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Sl(n)}, target=${Sl(a)}`);await wr.mkdir(Pt.dirname(r),{recursive:!0}),await wr.rename(i,r)}}async function H$(e,t,r){let i=await qa(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 Lv(e,t,"rolling-back");await oi(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 cY(e,o):await sY(e,n,o,r));return await oi(e,n.id,"rollback-completed"),n=await Lv(e,n,"rolled-back"),n}async function T$(e,t,r){let i=await Mt(e,r.target);if(r.type==="write"){let n=await Nn(e,t,r,i),a=await gi({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 bt({paths:e,file:i,operation:r,record:a,label:`Archive commit target ${r.target}`});return}await _r({target:i,expectedHash:null,label:`Archive commit target ${r.target}`})}async function lY(e,t){for(let r of t.operations){if(r.type==="move")continue;let i=await Mt(e,r.target),n=await Nn(e,t,r,i);if(await Ve(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await T$(e,t,r),r.expectedTargetHash!==null){let a=await gi({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 Ve(n.originalQuarantine)&&await Is({paths:e,file:n.originalQuarantine,operation:r,record:a,label:`Archive commit original quarantine ${r.target}`})}await lS({paths:e,journal:t,operation:r,target:i})}for(let r of t.operations)r.type!=="move"&&await T$(e,t,r)}async function Vv(e,t,r){return r==="commit"&&await lY(e,t),await oi(e,t.id,r),r==="commit"?Lv(e,t,"committed"):t}Oe();To();hi();var mde=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});ci();zo();Fe();Z();cr();es();var Wv=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"},xf=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 q$(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 El.resolve(e.nativeRoot,...r.target.split("/"))}async function L$(e,t,r){let i=await qa(e,t.id);if(i.some(v=>v.type==="archive-finalized"))return;let n=i.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(w=>w.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await Wi(q$(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=q$(e,t),o=El.join(a,ct),s=await B_(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=Q(e,s.name),l=await At(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 v=bT(vn,l,new Set,qk,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=kT(vn,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},qk,void 0)}let d=ae(`archive:${t.id}:${s.name}`),f=await dr(c,u.trajectoryRef),p=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(p.length>1||p.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let h=p.find(v=>v.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(h&&t.schema==="comet.native.transaction.v2"&&(!uY(h.data,m)||h.runId!==u.runId||h.timestamp!==t.createdAt||h!==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 Vv(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await gc(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await M_(o,v)}h||(h=await ho({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await As({changeDir:c,run:u,trajectoryOffset:h.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await rs(c,u),await ff(e,s.name),t.schema==="comet.native.transaction.v2"?await Vv(e,t,"archive-finalized"):await gc(e,t,"archive-finalized")}async function dS(e,t){let r=je(e,t);try{let i=await F$.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${r}`);return await T(e.runtimeDir,r),await F$.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 dY(e,t,r){if(t.schema==="comet.native.transaction.v2"){if(!(await qa(e,t.id)).some(c=>c.type==="operation-started")){let c=await qv({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new xf(c,"Native Archive facts changed before the first transaction operation")}let o=await D$(e,t,{...r,beforeArchiveChangeMove:async c=>{await r?.beforeArchiveChangeMove?.(c);let l=await Me(e,t.change),u=await Fv({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 L$(e,o,r);let s=await Vv(e,o,"commit");return{journal:s,runtimeCleanupWarning:await dS(e,s.change)}}let i=await $C(e,t);await L$(e,i,r);let n=await gc(e,i,"commit");return{journal:n,runtimeCleanupWarning:n.change?await dS(e,n.change):null}}function fY(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(El.resolve(t.projectRoot)!==El.resolve(e.projectRoot)||El.resolve(t.nativeRoot)!==El.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function M$(e){return A(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await An(e.paths,"archive",`recover archive ${e.transactionId}`);try{let r=await Rr(e.paths,e.transactionId),i=r.schema==="comet.native.transaction.v2"?await uS(e.paths,e.transactionId):r;return fY(e.paths,i),i.status==="committed"?(i.change&&await dS(e.paths,i.change),i):i.status==="rolled-back"?i:e.strategy==="continue"?(await dY(e.paths,i)).journal:i.schema==="comet.native.transaction.v2"?H$(e.paths,i):Yh(e.paths,i)}finally{await In(t)}},{allowedTransactionId:e.transactionId})}Z();ot();function he(e,t,r){return e==="zh-CN"?r:t}var fS={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function B$(e,t){return typeof e=="string"&&fS[e]?he(t,fS[e].en,fS[e].zh):typeof e=="string"?e:""}function pS(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 pY(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 V$(e,t){let r=[];e.failed>0&&r.push(he(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(he(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(he(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=he(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function W$(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 hS(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function hY(e,t,r){return e==="done"?he(r,"complete","已完成"):e==="await-user"?he(r,"waiting for a user decision","等待用户决定"):e==="blocked"?he(r,"paused: needs attention","已暂停,需要处理"):t?he(r,"waiting for a user decision","等待用户决定"):he(r,"ready to continue","可继续推进")}function mY(e,t,r){let i=hS(e),n=[];r&&n.push(r);let a=he(i,`Change ${e.change}`,`需求 ${e.change}`),o=B$(e.phase,i),s=hY(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(V$(t,i));let c=e.userCommunication,l=z$(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function z$(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:he(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:he(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:he(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function vY(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function gY(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=B$(e.phase,t),n=e.status==="await-user"?he(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?he(t,"paused","已暂停"):e.status==="done"?he(t,"complete","已完成"):he(t,"in progress","进行中"),a=pS(e.acceptance)?`${he(t,", ",",")}${V$(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function wY(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 yY(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 NY(e){if(e.healthy){let i=e.repaired?he("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):he("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=bY(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:he("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:he("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function bY(e){return W$(e)?z$(e,hS(e)):void 0}function J$(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(yY(t))return NY(t);if(vY(t)){let i=wY(t.items);return{summary:[t.total===t.items.length?he(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):he(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>gY(a,i))].join(`
|
|
326
|
+
`)}}let r=t.continuation;if(W$(r)){let i=hS(r),n=mY(r,kY(t),EY(t,i));return SY(t)==="unconfirmed"?{...n,summary:`${n.summary}${he(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:he(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 kY(e){if(pS(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(pS(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return pY(r.acceptance)}return null}function SY(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function EY(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return he(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?he(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function G$(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:he("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:he("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:he("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:he("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:he("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:he("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:he("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:he("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:he("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Pm();var K$=["--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."],mS=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","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:K$,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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
|
|
327
327
|
comet native spec remove <change-name> <capability>
|
|
328
328
|
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:["disassociate <change-name> Revoke a capability association and return to Shape.","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 disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],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 canonical artifact paths, 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 canonical artifact paths and 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>]
|
|
329
329
|
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>]
|
|
330
330
|
comet native next <change-name> --runner-input <json-file> [--validate-only]`,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, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, verification_checks, known_limits, optional review. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan is reused without executing the same plan twice when dispatch-verifier receives the unchanged plan. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," 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}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus 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]
|
|
331
331
|
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 zv(e,t){return`${e}:
|
|
332
332
|
${t.map(r=>` ${r}`).join(`
|
|
333
|
-
`)}`}function
|
|
333
|
+
`)}`}function RY(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return mS[r]||t.length>1&&mS[t[0]]?.subcommands?r:t[0]}function vS(e=[]){let t=RY(e),r=mS[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",zv("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",zv("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...K$];return n&&n.length>0&&i.push("",zv("Options",n)),i.push("",`Output:
|
|
334
334
|
${r.output}`),r.examples&&i.push("",zv("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
335
335
|
`)}
|
|
336
|
-
`}}var
|
|
337
|
-
`}function V(e,t,r){return{command:e,exitCode:0,data:t,text:r??Z$(t)}}function
|
|
336
|
+
`}}var PY=vS().usage;var Y$=10*1024*1024,I=class extends Error{};function Tt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new I(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Pe(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new I(`${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 I(`${t} requires a value`);return e.splice(i,2),n}function $e(e){if(e.length>0)throw new I(`Unexpected argument: ${e[0]}`)}function at(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new I(`${t} is required`);return r}function Jv(e,t="en"){let r=Pe(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new I("--language must be en or zh-CN");return r}function gS(e,t){let r=Cf.normalize(U$(e)),i=Cf.normalize(U$(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function U$(e){let t=Cf.resolve(e);try{return xY.native(t)}catch{return t}}function CY(e){let t=Cf.resolve(e),r=ie(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=ie(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!gS(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||gS(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:gS(process.cwd(),r.currentWorktreeRoot)?Cf.resolve(process.cwd()):r.currentWorktreeRoot}async function X$(e){return e?CY(e):gh(process.cwd())}async function yr(e){let t=await Tx({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}async function Q$(e){let t=await te(e);return Se(e,t?.native.artifact_root??"docs")}function Z$(e){return JSON.stringify(e,null,2)+`
|
|
337
|
+
`}function V(e,t,r){return{command:e,exitCode:0,data:t,text:r??Z$(t)}}function _Y(e,t){if(t instanceof hd)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof I)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Wv)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 xf)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof cd)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 Ic)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 Xa)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof jc)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 wo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Rf)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 Rl(e,t){let r=_Y(e,t),i=r.error;if(!i)return r;let n=G$({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function AY(e,t,r=!1){let i=e.envelope??J$(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:hT(e.data,e.executionCwd),...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}})+`
|
|
338
338
|
`}:e.error?{exitCode:e.exitCode,stderr:i?gT(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:vT(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Z$(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
339
339
|
${ra.details}
|
|
340
340
|
${JSON.stringify(e.data,null,2)}
|
|
341
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function wS(e,t,r=!1){let i=
|
|
341
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function wS(e,t,r=!1){let i=AY(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}async function eO(e,t){let r=at(e,"change name"),i=Tt(e,"--dry-run"),n=Pe(e,"--expect-preflight"),a=Tt(e,"--confirmed"),o=Pe(e,"--finish"),s=Pe(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new I("--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 I("--finish must be merge, push, pull-request, or keep");let l=await yr(t),u=await Ae(l.paths,r),d=await ta(l.paths,r),f=u?await Oa(l.paths,{kind:"archive",change:r}):null,p=f?.kind==="archive"?f.journal.spec_changes.slice(0,f.journal.next_spec_index):[],h=u?!1:await Hj(l.paths,r);if(d&&!u&&!h){if(n)throw new I("A recorded workspace finish does not use preflight hashes");if(s)throw new I("--serial-first is only valid while archiving an active change");if(o&&d.result?.action&&o!==d.result.action)throw new I(`Recorded workspace finish is '${d.result.action}'; retry it without changing --finish`);if(i)return{command:"archive --dry-run",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:d.result,recovery:d.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"]},error:{code:"conflict",message:d.result?.message??"Native workspace finish is still pending"}};if(!a)throw new I("Native workspace finish is pending; rerun Archive with --confirmed after resolving the blocker");$e(e);let v=d.archiveDir;if(!v||!q(l.paths.archiveDir,Pl.resolve(v))||Pl.resolve(v)===Pl.resolve(l.paths.archiveDir))throw new Error("Native workspace finish journal has no safe archived change directory");let g=await gf(l.paths,Pl.join(v,"comet-state.yaml"));if(g.state.name!==r||!g.state.archived||g.state.status!=="done")throw new Error("Native workspace finish journal does not match a completed Archive record");let w;try{w=await vf({paths:l.paths,state:g.state,archiveDir:v,pullRequestFinish:l.config.native.finish?.pull_request})}catch(k){let b=k instanceof Error?k.message:String(k),R={...d.result??{action:g.state.workspace.finish??"keep",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:null,cleanup:{performed:!1,reason:null},blockedPaths:[],diagnosticArgs:null,recoveryArgs:null},status:"blocked",message:b,recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await _s(l.paths,{...d,status:"blocked",result:R,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:g.state,archiveDir:v,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:R,continuation:{disposition:"blocked",reason:b,commandArgs:R.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:b}}}if(w)try{let k=await Pk({paths:l.paths,state:g.state,name:r,archiveDir:v,transactionId:d.transactionId,plan:w});return await vl(l.paths,r),V("archive",{archived:!0,state:g.state,archiveDir:v,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:k,continuation:L(g.state)},`Completed pending workspace finish for Native change ${r}
|
|
342
342
|
`)}catch(k){if(!(k instanceof ml))throw k;return await _s(l.paths,{...d,status:"blocked",result:k.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:g.state,archiveDir:v,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:k.result,continuation:{disposition:"blocked",reason:k.message,commandArgs:k.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:k.message}}}return await vl(l.paths,r),V("archive",{archived:!0,state:g.state,archiveDir:v,workspaceFinish:g.state.workspace.finish,workspaceFinishResult:null,continuation:L(g.state)},`Native change ${r} is already archived
|
|
343
343
|
`)}if(u||h||d){if(n)throw new I("Portable Native Archive does not use preflight hashes");if(i&&a)throw new I("--confirmed is only valid when executing Archive");if(s&&s!==r)throw new I("--serial-first must name the change being archived");if(!i&&c&&!a)throw new I("--finish without --dry-run requires --confirmed");$e(e);let v=u&&!i&&f?.kind!=="archive"?await Rs({paths:l.paths,name:r}):null,g=v?.state??(u?await O(l.paths,r):null);if(!i&&a&&c&&g&&g.workspace.isolation!=="current"&&g.workspace.finish===null&&(g=await cv({paths:l.paths,name:r,finish:c})),v?.action==="reverify"||v?.action==="await-user")return V(i?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:L(v.state)},`${v.message}
|
|
344
344
|
`);if(i){if(!g)return V("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}
|
|
345
345
|
`);c&&(g=await cv({paths:l.paths,name:r,finish:c}));let S=await hk({paths:l.paths,name:r});if(S.requiresReverification)return V("archive --dry-run",{...S,archived:!1,ready:!1,state:g,blockers:S.blockers,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:L(g)},`Native Archive preview requires fresh verification after delta remerge; no rebase was written during dry-run
|
|
346
346
|
`);let E="capabilities are also declared by:",N=S.blockers.filter(Le=>!Le.startsWith(E)),P=[],C=g.workspace.isolation!=="current"&&g.workspace.finish===null;if(C&&N.push("Native branch and worktree isolation require a workspace finish choice"),!C)try{await vf({paths:l.paths,state:g,appliedSpecChanges:p,pullRequestFinish:l.config.native.finish?.pull_request})}catch(Le){let Ee=Le.message;N.push(Ee),P.push({message:Ee,paths:Le instanceof Vi?Le.paths:[],workspaceRoot:Le instanceof Vi?Le.workspaceRoot:l.paths.projectRoot})}let x=S.capabilityPeers.length>0&&s!==r,D=x&&N.length===0?L(g,null,{archiveMode:"preview"}):null,se=D?{...D,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],requiresUserDecision:!0,userCommunication:{required:!0,message:g.language==="zh-CN"?`当前规格也由 ${S.capabilityPeers.join(", ")} 修改。是否先归档 ${r}?其他 change 随后需要对齐最新规格。`:`The same specifications are changed by ${S.capabilityPeers.join(", ")}. Archive ${r} first? The other changes must then align with the latest specifications.`,suggestedReply:g.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 ${S.capabilityPeers.join(", ")}`,inputOptions:[],requiredInputs:[]}],runnerAction:{...D.runnerAction,kind:"none"}}:C?L(g):L(g,null,{archiveMode:"preview",archiveBlockers:N}),U=[...N,...x?[`${E} ${S.capabilityPeers.join(", ")}`]:[]];return V("archive --dry-run",{...S,ready:U.length===0,blockers:U,...P.length>0?{workspaceFinishBlockers:P}:{},workspaceFinish:g.workspace.finish,continuation:s===r&&se.commandArgs?{...se,commandArgs:[...se.commandArgs,"--serial-first",r]}:se},`Native Archive preview: ${U.length===0?"ready":"blocked"}
|
|
347
|
-
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new I("archive requires --confirmed when native.archive_confirmation is required");if(g&&g.workspace.isolation!=="current"&&g.workspace.finish===null){let S=L(g);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:S},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let w=null;if(g)try{w=await vf({paths:l.paths,state:g,appliedSpecChanges:p,pullRequestFinish:l.config.native.finish?.pull_request})}catch(S){let E=S.message,N=S instanceof Vi?S.paths:[],P=S instanceof Vi?S.workspaceRoot:l.paths.projectRoot,C={action:g.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:P,cleanup:{performed:!1,reason:null},blockedPaths:N,message:E,diagnosticArgs:["git","-C",P,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:g,workspaceFinish:g.workspace.finish,workspaceFinishResult:C,continuation:L(g,null,{archiveMode:"blocked",archiveBlockers:[E]})},error:{code:"conflict",message:E}}}let k=!1;w&&(await _s(l.paths,{schema:Cs,name:r,transactionId:d?.transactionId??(f?.kind==="archive"?f.journal.id:void 0)??
|
|
347
|
+
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new I("archive requires --confirmed when native.archive_confirmation is required");if(g&&g.workspace.isolation!=="current"&&g.workspace.finish===null){let S=L(g);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:S},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let w=null;if(g)try{w=await vf({paths:l.paths,state:g,appliedSpecChanges:p,pullRequestFinish:l.config.native.finish?.pull_request})}catch(S){let E=S.message,N=S instanceof Vi?S.paths:[],P=S instanceof Vi?S.workspaceRoot:l.paths.projectRoot,C={action:g.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:P,cleanup:{performed:!1,reason:null},blockedPaths:N,message:E,diagnosticArgs:["git","-C",P,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:g,workspaceFinish:g.workspace.finish,workspaceFinishResult:C,continuation:L(g,null,{archiveMode:"blocked",archiveBlockers:[E]})},error:{code:"conflict",message:E}}}let k=!1;w&&(await _s(l.paths,{schema:Cs,name:r,transactionId:d?.transactionId??(f?.kind==="archive"?f.journal.id:void 0)??IY(),archiveDir:d?.archiveDir??null,status:"pending",result:null,updatedAt:new Date().toISOString()}),k=!0);let b;try{b=await mf({paths:l.paths,name:r,...s?{serialFirstChange:s}:{}})}catch(S){if(S instanceof pl)return(k||d)&&await vl(l.paths,r),V("archive",{archived:!1,state:S.state,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:L(S.state)},`Native Archive requires fresh verification after delta remerge
|
|
348
348
|
`);if(!(S instanceof hf)||((k||d)&&await vl(l.paths,r),!g))throw S;let E=await hk({paths:l.paths,name:r}),N=S.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...E,workspaceFinish:g.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:S.message,commandArgs:N,inputOptions:S.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:S.message}}}if(g=b.state,!w&&g)try{w=await vf({paths:l.paths,state:g,archiveDir:b.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request})}catch(S){let E=S.message,N=S instanceof Vi?S.paths:[],P=S instanceof Vi?S.workspaceRoot:l.paths.projectRoot,C={action:g.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:P,cleanup:{performed:!1,reason:null},blockedPaths:N,message:E,diagnosticArgs:["git","-C",P,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await _s(l.paths,{schema:Cs,name:r,transactionId:b.transactionId,archiveDir:b.archiveDir,status:"blocked",result:C,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{...b,workspaceFinish:g.workspace.finish,workspaceFinishResult:C,continuation:{disposition:"blocked",reason:E,commandArgs:C.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:E}}}w&&await _s(l.paths,{schema:Cs,name:r,transactionId:b.transactionId,archiveDir:b.archiveDir,status:"pending",result:null,updatedAt:new Date().toISOString()});let R=null;if(w)try{R=await Pk({paths:l.paths,state:b.state,name:r,archiveDir:b.archiveDir,transactionId:b.transactionId,plan:w})}catch(S){if(!(S instanceof ml))throw S;return await _s(l.paths,{schema:Cs,name:r,transactionId:b.transactionId,archiveDir:b.archiveDir,status:"blocked",result:S.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{...b,workspaceFinish:b.state.workspace.finish,workspaceFinishResult:S.result,continuation:{disposition:"blocked",reason:S.message,commandArgs:S.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:S.message}}}w&&await vl(l.paths,r);let y=R?.merged===!0?await ck({childPaths:l.paths,childState:b.state}):null;return V("archive",{...b,artifactRefs:["brief.md",...b.state.verification_report?[b.state.verification_report]:[]].map(S=>Pl.relative(t,Pl.join(b.archiveDir,S)).replaceAll("\\","/")),workspaceFinish:b.state.workspace.finish,workspaceFinishResult:R,...y?{parentAdvance:y.parentAdvance}:{},...y?.parentState?{parentState:y.parentState}:{},continuation:L(y?.parentState??b.state)},`Archived Native change ${r} to ${b.archiveDir}
|
|
349
349
|
`)}if(s)throw new I("--serial-first is only valid for portable Native changes");if(!i&&c&&!a)throw new I("--finish without --dry-run requires --confirmed");if($e(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 m=await Bi({paths:l.paths,name:r});return V("archive",{migration:{from:"legacy",to:m.schema,completed:!0},state:m,continuation:L(m)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
|
|
350
|
-
`)}import{createHash as
|
|
351
|
-
`);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
|
|
352
|
-
`}}import{promises as t0}from"node:fs";import Df from"node:path";fr();import{promises as og}from"fs";import Ot from"path";ot();import{promises as r4}from"fs";Vu();Qe();Z();async function cO(e,t){let r=[],i=Q(e,t.name),n=Ia(i,Lr.stateRef),a;try{a=await At(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=Ia(i,a.trajectoryRef),s=await Cc(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 dr(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=Ia(i,a.checkpointRef);try{let u=await xc(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}Ba();var BY=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function VY(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function WY(e){return e?e.map(VY).join(" "):null}function zY(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 wi(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 JY(e){return e.map(t=>wi(t,[],null))}function GY(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[wi("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(wi("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(wi("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),wi("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(wi("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(wi("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),wi("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Xt(e,t){let r=t.commandArgs===void 0?zY(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?WY(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??JY(t.requiredInputs??[])}}function Kv(e){let r=(e.findings??[]).filter(d=>!_c(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||BY.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 Xt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Xt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[wi("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Xt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Xt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Xt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Xt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[wi("summary",["--summary"],"<summary>")]});if(n)return Xt(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 Xt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[wi("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Xt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Xt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Xt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Xt(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"),Xt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[wi("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Xt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Xt(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=GY(e.state);return Xt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import _f from"path";Z();var lO=8,KY={"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 UY(e){let t=KY[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"}:_c(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 YY(e,t,r){if(!r.path)return null;let i;if(_f.isAbsolute(r.path)?i=_f.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=_f.resolve(pe(e,t.name),...r.path.split(/[\\/]/u)):i=_f.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=_f.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function XY(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 NS(e){return e.findings.map(t=>{let r=UY(t.code);return{code:t.code,message:t.message,severity:r.severity,path:YY(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:XY(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 bS(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,lO),truncated:t.length>lO}}var uO=240,dO=8,Uv=50;function fO(e){let t=Array.from(e);return t.length<=uO?e:`${t.slice(0,uO-1).join("")}…`}function QY(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function ZY(e){let t=[...new Set(e.map(QY))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,dO),reasonCount:e.length,codesTruncated:t.length>dO};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Uv),reasonsTruncated:e.length>Uv}}}async function pO(e){let t=null;try{let s=await go(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:vo(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:vo(e.paths,e.state.name)}}let r=await d$({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=ZY(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Sf.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:fO(r.checkpoint.summary),nextAction:fO(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:Sf.maxArtifacts}}Z();hi();el();Wn();async function e4(e,t){let r=Q(e,t.name),i=await At(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 xc(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 dr(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function t4(e,t){let r=await e4(e,t);return{committed:r,latest:MT(r),history:LT(r)}}async function hO(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await t4(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)}}hi();cr();Z();function Af(e,t){try{return _i(e,t)}catch{return}}var i4=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Qr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function kS(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function n4(e){return(await uf(e))?.change??null}function a4(e,t,r=!1,i){return Kv({state:e,archiveReady:t,evidenceRetreat:r}).command}async function o4(e,t){let r=pe(e,t.name),i=[...(await pd(r,t.brief)).findings,...(await sA(e,t)).findings,...await cO(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ec(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 im(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 aa({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 na(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 MN(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 xl(e,t,r){let i=await n4(e)===t,n=await ju(e,t),a=await od(e,t),o;try{let N=await di(e,t);if(N.status==="migration-required"&&N.state)return{name:t,artifacts:Af(e,t),phase:N.state.phase,revision:"revision"in N.state?N.state.revision:null,approval:N.state.approval,verificationResult:N.state.verification_result,specChanges:N.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:N.schema,migrationRequired:!0,minimumRuntimeVersion:N.minimumRuntimeVersion,error:N.message};if(N.status!=="current"||!N.state)return{name:t,artifacts:Af(e,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:N.schema,minimumRuntimeVersion:N.minimumRuntimeVersion,error:N.message??`Native change ${t} is incompatible`};o=N.state}catch(N){return{name:t,artifacts:Af(e,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:N.message}}if(n.status!=="available"){let N={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},P=NS({paths:e,state:o,findings:[N]}),C=Kv({state:o,findings:P});return{name:o.name,artifacts:Af(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:C.command,archiveReady:!1,inspection:{freshness:"stale",codes:[N.code],reasonCount:1,codesTruncated:!1},findingSummary:bS(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:C,workspace:a,runtime:n,...r?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:N.message}:{}}}let s=await pO({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await hO(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let N=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:N,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 N=await aa({changeDir:pe(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let D=await vs(e,o.name,o.verification_evidence);for(let se of D.acceptanceTrace.entries)P.set(se.acceptanceId,se.status==="failed"?"failed":se.status==="missing"?"missing":"satisfied")}let C=aC({criteria:N.contract.acceptance,acceptanceHash:N.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),x=C.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",C.nextCursor,"--project-root",e.projectRoot]:null;u={...C,...x?{nextPageCommand:kS(x),nextPageArgs:x}:{}}}catch(N){if(r.acceptanceCursor)throw N;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let N=await Pv(e,o.name,{tolerateInvalidSiblings:!0});d.push(...N.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let N=await Gt(e,o.name);if(N)if(N.schema==="comet.native.workspace.v3"){let P=await sn({paths:e,identity:N});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await za({paths:e,identity:N});f.push(...P.findingCodes.map(C=>({code:C,message:`Native workspace advisory changed: ${C} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],h=!1;if(o.phase==="verify"){let N=await k$({paths:e,state:o});h=N.freshness!=="fresh",p.push(...N.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,v=[];if(o.phase==="archive")try{m=await qv({paths:e,name:o.name}),v.push(...m.findingCodes.map(N=>({code:N,message:`Native Archive is blocked: ${N}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await o4(e,o),...s.findings,...d,...f,...p,...l,...v].filter((N,P,C)=>C.findIndex(x=>x.code===N.code&&x.path===N.path)===P),w=NS({paths:e,state:o,findings:g}),k=w.filter(N=>!_c(N.code)),b=o.phase==="archive"&&m?.ready===!0&&k.length===0,R=h||o.phase==="archive"&&(m?.findingCodes??[]).some(N=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(N)),y=w.some(N=>N.code==="trajectory-tail-incomplete"||N.code==="trajectory-invalid"||N.requiredAction==="return-to-bound-working-directory"||N.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=w.find(N=>N.severity==="error");return{name:o.name,artifacts:Af(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:y||S?null:a4(o,b,R,r?.clarificationMode),archiveReady:b,inspection:s.inspection,findingSummary:bS(w),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Kv({state:o,findings:w,archiveReady:b,evidenceRetreat:R,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:Uv,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:w.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function SS(e){let t;try{t=await qr({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await r4.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Qr.maxChanges))throw new Error(`Native status exceeds ${Qr.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}function Yv(e,t){let r=t.toString(36),i=j("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${r}.${i}`}function s4(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=i4.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=j("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 c4(e,t){let r=await SS(e),i=j("comet.native.status-names.v1",r),n=s4({namesHash:i,total:r.length,cursor:t?.cursor}),a=await Promise.all(r.slice(n,n+Qr.maxItems).map(u=>xl(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?Yv(i,f):null,nextPageCommand:f<r.length?kS(["comet","native","status","--cursor",Yv(i,f)]):null,nextPageArgs:f<r.length?["comet","native","status","--cursor",Yv(i,f)]:null,limits:{...Qr}};if(Buffer.byteLength(JSON.stringify(p),"utf8")>Qr.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?Yv(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?kS(l):null,nextPageArgs:l,limits:{...Qr}}}async function ES(e,t){return(await c4(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}Qc();import{createHash as x4,randomUUID as C4}from"node:crypto";import{constants as _S,promises as Ie}from"node:fs";import Ue from"node:path";ot();hi();Fe();Z();var Zv=Ji(Ri(),1);Oe();import{randomUUID as l4}from"crypto";import{promises as yO}from"fs";import PS from"path";import{isDeepStrictEqual as xS}from"util";ci();Fe();Z();cr();Ba();cc();var Ts=/^[a-f0-9]{64}$/u,u4=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),d4=new Set(["sourceHash","targetHash","nextJournal"]),f4=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),mO=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),p4=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Xv(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function vO(e){return JSON.stringify(e,null,2)+`
|
|
353
|
-
`}function CS(e){return e.schema===st?qu(e):$n(e)}function RS(e,t){return{...e,schema:st,minimum_runtime_version:2,revision:t}}function
|
|
354
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(i&&a.schema===st?Cl(a,u.previousState)||Cl(a,u.nextState):a.schema===it&&(wO(a,u.previousState)||wO(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!==it)throw new Error("Schema migration transition supersede target schema is invalid");s=v4(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");Xv(r.runRetreat,p4,"Schema migration Run retreat");let l=r.runRetreat,u,d;try{u=Wa(l.previousRun),d=Wa(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Ts.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!==it||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 jf(e,t){let r=If(e,t),i=B(e,r);await T(i,r);try{let n=await Vh({root:i,file:r,maxBytes:null,label:"Native schema migration journal"});return g4(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function w4(e,t,r){let i=await Ec(e,t),n=i?await im(e,i):await nm(e,{now:new Date(r),origin:"legacy-migration"});if(!n.complete){let a=yN(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 jc(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}i===null&&await NN(e,t,n)}async function NO(e){try{return await si(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function y4(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 bO(e,t){let r=t.transitionSupersede,i=Q(e,t.change),n=await dr(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&&!xS(o.event,y4(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 N4(e,t,r){if(!t.transitionSupersede)return;let i=Yt(e,t.change),n=await NO(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=Q(e,t.change),o=await At(a),s=await bO(e,t),c=await xc(a,t.transitionSupersede.nextRun.checkpointRef);if(!r||!o||!sa(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!==ae(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function b4(e,t,r){let i=t.transitionSupersede;if(!i)return;let n=Q(e,t.change),a=await At(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!sa(a,i.nextRun)){if(!sa(a,i.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rs(n,i.nextRun),await r?.afterRunStateWritten?.(t)}if(!sa(await At(n),i.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await bO(e,t);if(o.sequence===null){let l=await ho({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 As({changeDir:n,run:i.nextRun,trajectoryOffset:o.sequence,evidenceHash:i.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t);let s=Yt(e,t.change),c=await NO(s);if(c!==null){if(c!==i.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await yO.rm(s),await r?.afterTransitionSuperseded?.(t)}}async function k4(e,t,r){if(!t.runRetreat)return;let i=Q(e,t.change),n=await At(i);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!sa(n,t.runRetreat.nextRun)){if(!sa(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rs(i,t.runRetreat.nextRun),await r?.afterRunStateWritten?.(t)}let a=await dr(i,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await ho({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 As({changeDir:i,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t)}async function S4(e,t,r){let i=await jf(e,t);if(!i)return null;if(await $c(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=PS.join(pe(e,t),ct),a=await si(n);if(await N4(e,i,a===i.targetHash),await w4(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 Ne(n,(0,Zv.stringify)(CS(i.nextState))),await r?.afterStateWritten?.(i)}if(i.transition){let o=Yt(e,t),s=await si(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 ve(o,i.transition.nextJournal),await r?.afterTransitionWritten?.(i)}}return await b4(e,i,r),await k4(e,i,r),await yO.rm(If(e,t),{force:!0}),i.nextState}async function E4(e){let t=Q(e.paths,e.state.name),r=await At(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=ae(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:r,nextRun:i,evidenceHash:n,eventData:{fromSchema:st,toSchema:it,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function R4(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=Cl(r,t.previousState),a=Cl(r,t.nextState);if(!n&&!a)throw new Error(`Native change ${r.name} does not match its v2 evidence transition`);let o=Q(e.paths,r.name),s=await At(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${r.name}`);let c=t.previousRun!==null&&sa(s,t.previousRun),l=sa(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 dr(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(!xS(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Qv(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},h=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=ae(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 si(Yt(e.paths,r.name)),transitionId:t.id,previousRun:h,nextRun:m,evidenceHash:v,eventData:{fromSchema:st,toSchema:it,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function P4(e){let t,r,i,n;if(e.state.schema===nr){if(t=RS(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Jo)throw new Error("Native v1 change has a transition from another schema generation");let s=h4(e.pendingTransition.journal);if(gO(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(gO(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=Yt(e.paths,e.name);r={sourceHash:await si(c),targetHash:ae(vO(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==jn)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 R4({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,i=l.plan}else{let l=m4(s);if(Cl(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Cl(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=Yt(e.paths,e.name);r={sourceHash:await si(u),targetHash:ae(vO(l)),nextJournal:l}}}else t=Qv(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await E4({paths:e.paths,state:e.state,migrationId:e.id}));let a=PS.join(pe(e.paths,e.name),ct),o=(0,Zv.stringify)(CS(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===nr?st:it,sourceHash:await si(a),targetHash:ae(o),createdAt:e.now.toISOString(),nextState:t,...r?{transition:r}:{},...i?{transitionSupersede:i}:{},...n?{runRetreat:n}:{}}}async function kO(e){return A(e.paths,`migrate schema for ${e.name}`,()=>wn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let r=await S4(e.paths,e.name,e.hooks);if(r?.schema===it)return r;let i=await di(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 $c(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!==nr&&n.schema!==st)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Kk(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 P4({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??l4()}),s=If(e.paths,e.name),c=B(e.paths,s);await T(c,s),await ve(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}es();ei();Wn();Md();el();var ca=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),$s=/^([a-f0-9]{64})\.json$/u,_4=/^\.([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,A4=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,eg=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function IS(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bn(e,t){return IS(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xO(e,t){return IS(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function _l(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Nr(e,t){return e<t?-1:e>t?1:0}function I4(e,t){let r=Ue.relative(e.projectRoot,t);if(r.length===0||Ue.isAbsolute(r)||r===".."||r.startsWith(`..${Ue.sep}`))throw new Error("Native evidence retention finding path is outside the project");return r.split(Ue.sep).join("/")}function CO(e,t){return Ue.join(Q(e,t),"evidence")}function tg(e,t){return I4(e,CO(e,t))}async function rg(e,t){let r=Ue.resolve(e),i=Ue.resolve(t);if(!q(r,i))throw new Error("Native evidence retention path escapes its managed change");let n=Ue.relative(r,i).split(Ue.sep).filter(Boolean),a=[],o=r;for(let s of["",...n]){s&&(o=Ue.join(o,s));let c=await Ie.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Ie.realpath(o);if(a.length>0&&!q(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,..._l(c)})}return a}async function yi(e){for(let t of e){let r=await Ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!IS(t,r)||await Ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function _O(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:Fi(e,t)}function SO(e){return e!==null&&A4.test(e)?[e]:[]}function j4(e,t,r,i){if(e==="snapshots")return{canonical:Gc(r,t),dependencies:[]};if(e==="scopes"){let a=Uc(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=Wm(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=Ld(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(SO));return{canonical:a,dependencies:[a.implementationScopeRef,vb(a.reportHash),...SO(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"||x4("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=Wd(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=Gn(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 bo(e){let t=await Ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let r=e.kind==="check-receipts"?null:pi;if(r!==null&&t.size>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let i=await Ie.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":_S.O_RDONLY|_S.O_NOFOLLOW|_S.O_NONBLOCK,a=await Ie.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(),Ie.lstat(e.file),Ie.realpath(e.file)]);if(await yi(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==i||!bn(_l(t),o)||!bn(_l(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===null?u.length:r+1-d,k=await a.read(u,0,Math.min(u.length,w),null);if(k.bytesRead===0)break;if(d+=k.bytesRead,r!==null&&d>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,k.bytesRead)))}let[f,p,h]=await Promise.all([a.stat(),Ie.lstat(e.file),Ie.realpath(e.file)]);if(await yi(e.directoryChain),!p.isFile()||p.isSymbolicLink()||h!==i||!bn(_l(o),f)||!bn(_l(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(m)}catch(w){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:w})}let g=j4(e.kind,e.hash,v,e.name);if(m!==JSON.stringify(g.canonical,null,2)+`
|
|
355
|
-
`)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:_l(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(Nr)}}finally{await a.close()}}async function EO(e){try{return await Ie.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function T4(e){let t=Q(e.paths,e.name),r=t,i=CO(e.paths,e.name);await T(B(e.paths,i),i);let n;try{let s=await rg(t,i);n=await Ie.readdir(i,{withFileTypes:!0}),await yi(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of eg){if(!n.some(f=>f.name===s))continue;let c=Ue.join(i,s),l=await rg(t,c),u=(await Ie.readdir(c,{withFileTypes:!0})).sort((f,p)=>Nr(f.name,p.name)),d=new Map;for(let f of u){let p=_4.exec(f.name);if(!p)continue;let h=d.get(p[1])??[];h.push(f),d.set(p[1],h)}for(let[f,p]of[...d.entries()].sort(([h],[m])=>Nr(h,m))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let h=p[0];if(!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${h.name}`);let m=Ue.join(c,f),v=$s.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${h.name}`);let g=_O(s,v),w=Ue.join(c,h.name),k=await bo({changeRoot:r,file:w,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),b=await EO(m),R=b?null:await bo({changeRoot:r,file:m,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:m,quarantine:w,document:k,action:b?"restore-original":"finish-linked-recovery",originalDocument:R})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Nr);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Al(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${ig(o)}`),path:tg(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Nr(c.ref,l.ref))){if(await yi(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await bo({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await bo({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!bn(s.originalDocument.identity,d.identity)||!bn(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Ie.rm(s.quarantine),await yi(s.document.directoryChain);continue}if(!await EO(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Ie.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!bn(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Ie.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await bo({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await bo({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!xO(s.document.identity,l.identity)||!bn(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Ie.rm(s.quarantine),await yi(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Al(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${ig(o)}`),path:tg(e.paths,e.name)}]}}async function $4(e,t){let r=Q(e,t),i=r,n=Ue.join(r,"evidence");await T(B(e,n),n);let a;try{let l=await rg(r,n);a=await Ie.readdir(n,{withFileTypes:!0}),await yi(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!eg.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Nr);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${ig(o)}`);let s=[],c=0;for(let l of eg){if(!a.some(p=>p.name===l))continue;let u=Ue.join(n,l),d=await rg(i,u),f=(await Ie.readdir(u,{withFileTypes:!0})).sort((p,h)=>Nr(p.name,h.name));await yi(d);for(let p of f){if(s.length>=ca.maxDocuments)throw new Error(`Native evidence store exceeds ${ca.maxDocuments} documents`);let h=$s.exec(p.name);if(!h||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let m=_O(l,h[1]),v=Ue.join(u,p.name);await T(B(e,v),v);let g=await bo({changeRoot:i,file:v,ref:m,kind:l,hash:h[1],name:t,directoryChain:d});if(c+=g.size,c>ca.maxScannedBytes)throw new Error(`Native evidence store exceeds ${ca.maxScannedBytes} scanned bytes`);s.push(g)}await yi(d)}return s}function RO(e,t){let r=new Set,i=[...e].sort(Nr).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(Nr).reverse())r.has(o)||i.push(o)}return r}function O4(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(Nr),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(Nr))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function D4(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=RO(t,i),a=new Set(n);for(let c of e)r-c.mtimeMs<ca.minimumAgeMs&&a.add(c.ref);for(let c of eg){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Nr(u.ref,d.ref)).slice(0,ca.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=RO(a,i),s=e.filter(c=>!o.has(c.ref)&&r-c.mtimeMs>=ca.minimumAgeMs).sort((c,l)=>Nr(c.ref,l.ref));return{candidates:O4(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function ig(e){let t=e.slice(0,ca.maxReportedRefs),r=e.length-t.length;return`${t.join(", ")}${r>0?`, ... (${r} more)`:""}`}function Al(e){let t=ca.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 AS(e,t,r,i){let n=t.candidates.map(a=>a.ref).sort(Nr);return{severity:"info",code:r?"evidence-retention-cleaned":"evidence-retention-candidates",message:Al(`${r?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${ig(n)}`),path:i}}async function PO(e,t){try{await Ie.lstat(t);return}catch(r){if(r.code!=="ENOENT")return}try{await Ie.rename(e,t)}catch{}}async function H4(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await yi(e.directoryChain);let r=await bo({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:$s.exec(Ue.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),i=await Ie.lstat(e.file),n=await Ie.realpath(e.file);if(!i.isFile()||i.isSymbolicLink()||!bn(e.identity,i)||!bn(e.identity,r.identity)||!q(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=Ue.join(Ue.dirname(e.file),`.${Ue.basename(e.file)}.${C4()}.gc`);await Ie.rename(e.file,a);try{let[o,s]=await Promise.all([Ie.lstat(a),Ie.realpath(a)]);if(await yi(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!xO(e.identity,o)||!q(e.directoryChain[0].realPath,s))throw await PO(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Ie.rm(a),await yi(e.directoryChain)}catch(o){throw await PO(a,e.file),o}}async function F4(e){if((await te(e.projectRoot))?.native.pending_root_move)return!0;let r;try{r=await Ie.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 Rr(e,i.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function q4(e,t){if(t)return[t];let r;try{r=await Ie.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(Nr)}async function L4(e,t){let r=await di(e,t);if(r.status!=="current"||!r.state||r.state.archived)return!0;let[i,n,a]=await Promise.all([na(e,t),jf(e,t),go(e,t)]);return i!==null||n!==null||a!==null}async function M4(e){if(await L4(e.paths,e.name))return[];let t=await di(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let r=await T4({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 $4(e.paths,e.name),a=D4(n,i,e.nowMs);if(a.candidates.length===0)return r.findings;let o=tg(e.paths,e.name);if(!e.repair)return[...r.findings,AS(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await H4(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...r.findings,...s.length>0?[AS(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Al(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...r.findings,AS(e.name,a,!0,o)]}async function AO(e){if(e.deferAll||await F4(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 q4(e.paths,e.name))try{a.push(...await M4({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Al(`Native evidence retention refused to clean ${o}: ${s.message}`),path:tg(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 A(e.paths,"prune Native evidence",()=>r(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Al(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}zo();Z();cr();Oe();ot();zo();Z();cr();es();import{createHash as B4,randomUUID as V4}from"crypto";import{promises as ko}from"fs";import De from"path";async function $t(e){try{return await ko.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function W4(e){let t;try{t=await ko.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 Rr(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 z4(e,t){for(let r of await ko.readdir(e.locksDir,{withFileTypes:!0})){let i=De.join(e.locksDir,r.name);if(De.resolve(i)!==De.resolve(t)&&(r.isFile()||r.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${i}`)}}async function J4(e){let t;try{t=await ko.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 Gt(e,r.name);if(i){await vm({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 G4(e){let t;try{t=await ko.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 Gt(e,r.name);if(i?.schema==="comet.native.workspace.v3"){let n=await sn({paths:e,identity:i});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(i){let n=await za({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 $f(e,t){let r=[];async function i(n){let a=await Er({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=De.join(n,s.name);if(t.excludedFiles?.has(De.resolve(c))){await a.verify();continue}let l=await ko.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:De.relative(e,c).split(De.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await Qo({root:e,file:c,label:`Native root file ${De.relative(e,c)}`});r.push({ref:De.relative(e,c).split(De.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 K4(e,t,r,i){await nn({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await Er({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=De.join(a,l.name);if(De.resolve(u)===De.resolve(r)){await s.verify();continue}let d=await ko.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=De.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await nn({root:i,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Ha({sourceRoot:e,source:u,targetRoot:i,target:f,maxBytes:null,label:`Native root move file ${De.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 Il(e,t,r,i){let n=await $f(e,{rejectSymlinks:!0,excludedFiles:r?new Set([De.resolve(r)]):void 0}),a=await $f(t,{rejectSymlinks:!0,excludedFiles:i?new Set([De.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 $O(e,t){return De.join(e.artifactRoot,`.comet-native-move-${t}`)}function U4(e,t){return De.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function Y4(e){return`${e}.removing`}function IO(e,t){return De.join(De.dirname(e),`.${De.basename(e)}.${t}.rollback-removing`)}function OO(e,t,r){return De.join(Uh(e,t).directory,`root-move-cleanup-${r}.json`)}function X4(e){return JSON.stringify(e,null,2)+`
|
|
356
|
-
`}function Q4(e){return B4("sha256").update(e).digest("hex")}function Z4(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("\\")||De.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 e9(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(Z4);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=De.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 t9(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=X4(t);return await Ne(OO(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),Q4(r)}async function r9(e){let t=await ht({root:e.paths.runtimeDir,file:OO(e.paths,e.id,e.cleanup.kind),maxBytes:null,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 e9(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function jS(e){let t=await $f(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 jO(e){return e.ref.split("/").length}async function i9(e){let r=[...await jS({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>jO(a)-jO(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=De.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Wh({root:e.projectRoot,file:a,maxBytes:null,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await nN({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 jS({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await nN({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function ng(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function DO(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 n9(e,t,r,i){for(let a of[e,t])try{let o=await Rr(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=De.join(r,"runtime","transactions",i,"transaction.json");try{let a=await ht({root:r,file:n,maxBytes:null,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 TO(e){let t=ng(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Dr(e.projectRoot,t),t}async function Tf(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=ng(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 Dr(e.projectRoot,r),r}async function ag(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 $t(e.target),a=await $t(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 t9({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await $f(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Tf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await r9({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await $t(e.target),a=await $t(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 EC({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 Tf({projectRoot:e.projectRoot,config:t,id:e.id})}return await jS({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Tf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Tf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await i9({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Tf({projectRoot:e.projectRoot,config:t,id:e.id})}async function HO(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await $t(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=Y4(e.staging);t=await ag({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 $f(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([De.resolve(e.lockFile)])}),await K4(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Il(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await TO({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await $t(e.destinationPaths.nativeRoot)){if(await $t(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Il(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await $t(e.staging))throw new Error("Native move staging tree is missing");await Il(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await ko.rename(e.staging,e.destinationPaths.nativeRoot)}t=await TO({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 $t(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=U4(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await $t(e.sourcePaths.nativeRoot)&&await Il(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await ag({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 J4(e.destinationPaths);let n=await Rr(e.destinationPaths,e.pending.id);await gc(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 Dr(e.projectRoot,o),o}async function FO(e){let t=await te(e.projectRoot)??Mo("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let r=Aa(e.toArtifactRoot);if(r===t.native.artifact_root)throw new Error(`Native artifact root is already ${r}`);let i=await Se(e.projectRoot,t.native.artifact_root),n=await Se(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 $t(i.nativeRoot))throw new Error(`Native source root does not exist: ${i.nativeRoot}`);if(await W4(i),await $t(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await An(i,"root-move",`move root to ${r}`),o=V4(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:r,stage:"copying"},c=DO({id:o,paths:i,now:e.now??new Date}),l=$O(n,o);try{if(await z4(i,a.file),await G4(i),await $t(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Dr(e.projectRoot,ng(t,s)),await uN(i,c),await e.hooks?.afterRootMoveStage?.("copying",c),await HO({projectRoot:e.projectRoot,config:ng(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 In(a)}}async function qO(e){let t=await te(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let i=await Se(e.projectRoot,r.fromArtifactRoot),n=await Se(e.projectRoot,r.toArtifactRoot),a=$O(n,r.id),o=await $t(i.nativeRoot)?i:n,s=await An(o,"root-move",`recover root ${r.id}`);try{let c;try{c=await n9(i,n,a,r.id)}catch(h){if(r.stage!=="copying"||!await $t(i.nativeRoot))throw h;let m=DO({id:r.id,paths:i,now:new Date});await uN(i,m),c={journal:m,paths:i}}if(e.strategy==="continue"){let h=await HO({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:h}}if(!await $t(i.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=IO(n.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await $t(n.nativeRoot)&&await Il(i.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await ag({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=IO(a,r.id);!t.native.pending_root_move?.cleanup&&await $t(a)&&await Il(i.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await ag({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 Rr(i,r.id);await Yh(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 Dr(e.projectRoot,p),{activeNativeRoot:i.nativeRoot,config:p}}finally{await In(s)}}es();var jl=4096,a9=4096,o9=1024;async function So(e,t,r){try{let i=await Er({root:B(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 sg(e,t){let r=new Map(e.map(i=>[Ot.resolve(i.file),{...i,file:Ot.resolve(i.file)}]));for(let{paths:i,file:n}of r.values()){let a;try{a=await Du(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 Wo(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}if(a.status==="unknown"){let o=await Wo(i,n,a,{allowAgedUnknown:!0});if(o.status==="removed"){t.push({severity:"info",code:"aged-unknown-recovery-lock-removed",message:"Removed a recovery lock whose owner could not be proven stale and was recorded over fifteen minutes ago",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"||a.status==="unknown"?(t.push({severity:"error",code:"lock-owner-unknown",message:"Native recovery lock owner cannot be proven stale; retry doctor --repair after the lock is older than fifteen minutes",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 s9(e,t){let r=df(e),i;try{await T(e.projectRoot,r);let n=await uf(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 Ae(e,i.change)?[]:(await Me(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 og.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 c9(e){let t=[];for(let r of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(B(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 l9(e,t){let r=[],i=[];for(let n of await So(e,e.transactionsDir,a9)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await Rr(e,n.name)}catch(o){r.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ot.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 Vo([e],`doctor archive recovery ${a.id}`,async()=>await sg([{paths:e,file:Ot.join(e.locksDir,"root-move.lock")},{paths:e,file:Ot.join(e.locksDir,"archive.lock")}],r)?(await M$({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 u9(e,t,r){let i=[];for(let n of await So(e,e.locksDir,o9)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ot.join(e.locksDir,n.name);try{let o=await Du(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"){let s=qy(o.owner);if(t&&s>=Ou&&r.length===0){let c=await Wo(e,a,o,{allowAgedUnknown:!0});if(c.status==="removed"){i.push({severity:"info",code:"aged-unknown-lock-removed",message:"Removed a Native lock whose owner could not be proven stale and was recorded over fifteen minutes ago",path:a});continue}if(c.status==="missing")continue;i.push({severity:"warning",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing takeover",path:a});continue}i.push({severity:"warning",code:"lock-owner-unknown",message:s>=Ou?"Native lock owner cannot be proven stale; run doctor --repair to take over this lock":`Native lock owner cannot be proven stale yet; retry doctor --repair after ${Math.ceil((Ou-s)/6e4)} more minutes`,path:a})}else if(o.status==="stale")if(t&&r.length===0){let s=await Wo(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 d9(e,t,r=5){let i=[],n=t?await ES(e,{maxVerifyFailures:r}).then(a=>a.filter(o=>o.name===t)):await ES(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:Ot.join(e.changesDir,a.name,ct)});continue}let o=await xl(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:Ot.join(e.projectRoot,s.path)}:{}})}return i}async function f9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{let a=await Cc(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 x_(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:Ot.join(Q(e,n),"trajectory.jsonl")})}return r}async function p9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=await ju(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=Lo(e,n),s=je(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 Vo([e],`migrate Runtime layout for ${n}`,async()=>{let c=await qr({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await og.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await qr({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await og.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 og.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 h9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{if(!await jN(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:Ac(e,n),repair:"migrate"});continue}let a=await Me(e,n);await H_({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:Ac(e,n)})}catch(a){r.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Ac(e,n)})}return r}async function m9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=If(e,n);try{let o=await jf(e,n),s=await di(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:Ot.join(e.changesDir,n,ct)});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:Ot.join(e.changesDir,n,ct),repair:"migrate"});continue}await kO({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:Ot.join(e.changesDir,n,ct)})}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 v9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a;try{a=await na(e,n)}catch(o){if(o instanceof bf)continue;r.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Yt(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Vo([e],`doctor transition recovery ${n}`,async()=>await sg([{paths:e,file:Ot.join(e.locksDir,"root-move.lock")},{paths:e,file:Ot.join(e.locksDir,`transition-${n}.lock`)}],r)?(await t$(e,n),!0):!1))continue;r.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Yt(e,n)})}catch(o){r.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Yt(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:Yt(e,n),repair:"continue"})}}return r}async function g9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=vo(e,n),o;try{o=await go(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 Vo([e],`doctor checkpoint recovery ${n}`,async()=>await sg([{paths:e,file:Ot.join(e.locksDir,"root-move.lock")},{paths:e,file:Ot.join(e.locksDir,`transition-${n}.lock`)}],r)?(await f$(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 Of(e){let t=e.repair??!1,r=[],i=e.paths,n;try{n=await te(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([Se(i.projectRoot,c.fromArtifactRoot),Se(i.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await sg([{paths:l,file:Ot.join(l.locksDir,"root-move.lock")},{paths:u,file:Ot.join(u.locksDir,"root-move.lock")}],r))return{healthy:!1,findings:r};let f=await qO({projectRoot:i.projectRoot,strategy:e.recoveryStrategy});i=await Se(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 c9(i);if(r.push(...o),o.length>0)return{healthy:!1,findings:r};let s=await l9(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return r.push(...s.findings),e.projectOnly||(r.push(...await p9(i,{name:e.name,repair:t})),r.push(...await m9(i,{name:e.name,repair:t})),r.push(...await h9(i,{name:e.name,repair:t})),r.push(...await f9(i,{name:e.name,repair:t})),r.push(...await v9(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),r.push(...await g9(i,{name:e.name,repair:t})),r.push(...await AO({paths:i,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),r.push(...await u9(i,t,s.unfinished)),r.push(...await s9(i,t)),e.projectOnly||r.push(...await d9(i,e.name,n?.native.max_verify_failures??5)),{healthy:r.every(c=>c.severity==="info"),findings:r}}sr();ln();Ya();Fe();import{promises as BO}from"node:fs";import VO from"node:path";import LO from"node:path";function MO(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function kt(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:MO(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:MO(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=>LO.relative(t.projectRoot,LO.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}Z();function WO(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function zO(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 JO(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:N9(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:b9(i,r)}))]:[]]}function GO(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 w9(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=i!==null||r.requestCheckRounds>0;return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:n?"confirmed":"unconfirmed",...n?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function cg(e,t,r=ie(e.projectRoot)){let 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:VO.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 TS(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=kt(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...L(t),disposition:"blocked",action:"archive",commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the reported Git blocker; do not treat this archived change as complete until it succeeds."},runnerAction:{...L(t).runnerAction,kind:"none"}}:L(t),c=e.details?JO(t,null,[]):[],l=zO(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?WO(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:_i(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:VO.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:GO(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.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:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function y9(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 lg(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function N9(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:lg(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function b9(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:lg(e.summary,t)??""}}async function Ar(e){let t=await ns(e),r=kt(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await nt({paths:e.paths,state:t.state}),a=await mn({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await J(e.paths,e.name,{diagnostics:!0}),s=o?{...cg(e.paths,t.state,e.gitContext),projectRoot:"."}:cg(e.paths,t.state,e.gitContext),c=L(t.state,n,{verifierExecutionRef:qc(t.state,t.local),...t.local?{verificationCheckPlans:dl(t.local,t.local.workspace.projectRoot)}:{}}),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?y9(e.paths,o):[],d=o?(()=>{let h=new Map(n?.children.map(y=>[y.name,y.status])??[]),m=y=>h.get(y.name)??y.status,v=o.children.filter(y=>m(y)==="pending"||m(y)==="ready").length,g=o.children.filter(y=>m(y)==="active"||m(y)==="verified").length,w=o.children.filter(y=>m(y)==="integrated"||m(y)==="archived").length,k=o.children.filter(y=>m(y)==="blocked"||m(y)==="needs-reverify").length,b=o.children.filter(y=>m(y)==="active"||m(y)==="blocked"||m(y)==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:lg(y.blocker,u)})),R=o.children.flatMap(({blocker:y})=>{let S=lg(y,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:w,blocked:k,active:b,agents:{working:o.children.filter(({task:y})=>y!==null).length,completed:w},risks:R,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&w===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let h=o?.stateVersion??0,m=JO(t.state,o,u),v=zO(e.cursor,t.state.state_version,h),g=m.slice(v,v+32),w=v+g.length<m.length?WO(t.state.state_version,h,v+g.length):null;return{items:g,nextCursor:w,supervisorStateVersion:h}})():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,artifacts:_i(e.paths,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:GO(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let h=w9(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...h?{verifierStartup:h}:{}}})(),...n?{childSummary:n.children.reduce((h,m)=>({...h,[m.status]:(h[m.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 KO(e){let t;try{t=await BO.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 BO.readFile(`${X(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"))}Xo();var k9=1800*1e3;async function la(e,t){let r=await nt({paths:e,state:t});return L(t,r)}async function UO(e,t){let r;try{r=await lt(G(e,t))}catch{return null}if(r?.execution?.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")return null;let i=await ul(r);if(i==="running")return null;let n=i==="orphaned"?`Native Runtime check operation ${r.execution.operationId} has no live owner or active check process`:`Native Runtime check operation ${r.execution.operationId} is running, but its owner process identity is unavailable`;return{severity:"error",code:"portable-check-execution-stuck",message:`${t}: ${n}; run comet native doctor ${t} --repair to recover it`,path:G(e,t),repair:"recover"}}async function YO(e,t,r){if(r.phase!=="shape"||r.status!=="await-user"||r.loop.next_action!=="confirm-shape")return null;let i=await Mi({paths:e,state:r});if(!i.drifted)return null;let n=i.reason??"Native confirmed requirements changed";return{severity:"error",code:"portable-shape-confirmation-drift",message:`${t}: pending Shape confirmation is stale (${n}); run comet native doctor ${t} --repair to reopen Shape`,path:gt(e,t),repair:"recover",repairCommand:`comet native doctor ${t} --repair`}}async function XO(e,t,r){if(r.archived||r.workspace.change_branch!==null)return null;let i;try{i=await It({changeDir:X(e,t),policy:"advisory"})!==null}catch{i=!0}if(!i)return null;let n=ie(e.projectRoot),a=n.isGitWorktree&&n.currentBranch!==null&&er(e.projectRoot,n.currentBranch)!==null,o=a&&Oc(e.projectRoot),s=a?await QN(e,t):[];return{severity:"error",code:"portable-supervisor-git-binding-missing",message:a?o?s.length>0?`${t}: the Supervisor change has no Git branch binding while active child tasks exist (${s.join(", ")}); finish or recover those tasks before rerunning the latest continuation`:`${t}: the Supervisor change has no Git branch binding; run comet native status ${t} --json and rerun its continuation to bind branch ${n.currentBranch} at the Shape confirmation boundary`:`${t}: the Supervisor change has no Git branch binding and the current Git baseline is dirty; commit or stash pending changes to restore a clean current working directory, then rerun the latest continuation`:`${t}: the Supervisor change requires Git; initialize a Git repository, commit to a branch, then rerun the latest continuation`,path:gt(e,t)}}async function S9(e){let t;try{t=await t0.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 E9(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function QO(e,t){let r;try{r=await t0.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}-${E9(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:Df.join(e.archiveDir,n.name)}:null}function R9(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()]}async function P9(e,t){let r=[];if(t!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))return r;let i=(n,a)=>r.push({name:n,message:a});return t!==void 0?await ta(e,t,{onError:i}):await kv(e,{onError:i}),r}function ZO(e,t){return{severity:"error",code:"portable-workspace-finish-journal-invalid",message:`Native workspace finish journal for ${t.name} is invalid (${t.message}); run comet native doctor ${t.name} --repair to quarantine it and resume from the preserved change or Archive record`,path:Df.join(e.transactionsDir,`workspace-finish-${t.name}.json`),repair:"continue",repairCommand:`comet native doctor ${t.name} --repair`}}function kn(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function e0(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Df.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function x9(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}function C9(e,t,r){let i=new Map(t.children.map(({name:a,status:o})=>[a,o]));return{severity:"error",code:"portable-supervisor-ready-dependencies-unmet",message:`Native Supervisor children are marked ready but their dependencies are not integrated: ${r.map(a=>{let o=a.dependsOn.filter(s=>i.get(s)!=="integrated");return`${a.name} (waiting on: ${o.join(", ")})`}).join("; ")}. Run doctor --repair to demote them to pending until their dependencies integrate.`,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}}async function _9(e,t){let r=[],i=[];for(let n of await NC(e)){let a=Yo(n);if(t&&a.change!==t)continue;let o=Df.join(e.transactionsDir,n);try{let s=await Ju(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 $S(e,t){let r=Tt(e,"--repair"),i=Pe(e,"--strategy");if(i!==void 0&&i!=="continue"&&i!=="rollback")throw new I("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();$e(e);let a=await Q$(t),o=await P9(a,n);if(n&&o.length>0){let d=ZO(a,o[0]);if(!r){let m=await Ae(a,n)?await Ar({paths:a,name:n,details:!0}):void 0;return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...m?{result:m,continuation:m.continuation}:{},findings:[d]})}let f=await Ek(a,n);if(await Ae(a,n)){let h=await O(a,n);return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,workspaceFinishJournal:{quarantined:f,finding:d},state:h,continuation:await la(a,h)})}return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,workspaceFinishJournal:{quarantined:f,finding:d}})}let s=await _9(a,n);if(n&&s.findings.length>0){if(i)throw new I("--strategy is only available to the legacy transaction doctor");let f=await Ae(a,n)?await Ar({paths:a,name:n,details:!0}):void 0;if(r&&s.transactions.length===1&&s.findings.length===1){if(s.transactions[0].kind==="archive"){let m=await mf({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:await la(a,m.state)})}let h=await Bi({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await la(a,h)})}return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...f?{result:f,continuation:f.continuation}:{},findings:s.findings})}if(n&&await Ae(a,n)){if(i)throw new I("--strategy is only available to the legacy transaction doctor");let[d,f]=await Promise.all([QO(a,n),vk(a,n)]);if(d){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[d],continuation:y.continuation})}if(f&&!r){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[e0(a,n)],continuation:y.continuation})}let p=await O(a,n),h=await XO(a,n,p);if(h){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[h],continuation:y.continuation})}let m=await mn({paths:a,state:p}),v=x9(n,m);if(v&&(m.status==="incompatible"||!r)){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[v],continuation:y.continuation})}if(r){if(f){let C=await Bi({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:C.schema,stateVersion:C.state_version},state:C,continuation:await la(a,C)})}let y=await sv({paths:a,name:n});if(y.repaired)return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:y,continuation:await la(a,y.state)});let E=(await lt(G(a,n)).catch(()=>null))?.execution;if(E&&E.stage==="verifying"&&E.actor==="verifier"&&E.status==="running"&&E.verifierStartedAt===void 0){let C=Date.now()-Date.parse(E.startedAt);if(C>=k9){let x=await O(a,n),D=Xm({state:x,summary:`Verifier dispatch registered ${Math.round(C/6e4)} minutes ago and never confirmed startup; doctor repair recorded the failure`}),se=await en({file:gt(a,n),expectedStateVersion:x.state_version,next:D,containedRoot:a.nativeRoot});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:{verifierTakeover:!0,waitedMinutes:Math.round(C/6e4)},continuation:await la(a,se)})}}let N=await Rs({paths:a,name:n,recoverUnknownRuntimeCheck:!0});if(N.reason==="execution-active")return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:N,continuation:await la(a,N.state)});let P=await A(a,`repair Native Supervisor dependencies ${n}`,async()=>{let C=await J(a,n),x=C?.children.filter(D=>D.status==="ready"&&!Mc(D.dependsOn,C.children))??[];if(x.length===0||!C)return[];for(let D of x)D.status="pending",D.blocker=null;return await oe(a,C),x.map(({name:D})=>D)});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,...P.length>0?{supervisorDependencyRepair:P}:{},result:N,continuation:await la(a,N.state)})}let g=await YO(a,n,p);if(g){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[g],continuation:y.continuation})}let w=await UO(a,n);if(w){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[w],continuation:y.continuation})}let k=await J(a,n,{diagnostics:!0}),b=k&&k.children.filter(y=>y.status==="ready"&&!Mc(y.dependsOn,k.children));if(k&&b&&b.length>0){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[C9(n,k,b)],continuation:y.continuation})}let R=await Ar({paths:a,name:n,details:!0});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:R,continuation:R.continuation})}if(n){if(r){let d=await Bi({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:d.schema,stateVersion:d.state_version},state:d,continuation:await la(a,d)})}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 c=await KO(a),l=s;if(c.length>0||l.findings.length>0||o.length>0){if(i)throw new I("--strategy is only available to the legacy transaction doctor");if(r){let N=await Of({paths:a,repair:!0,projectOnly:!0}),P=[],C=[];for(let U of o)C.push({change:U.name,quarantined:await Ek(a,U.name)});for(let U of l.transactions)U.kind==="archive"?await mf({paths:a,name:U.change}):await Bi({paths:a,name:U.change}),P.push({kind:U.kind,change:U.change,transactionId:U.journal.id});let x=[];for(let U of c){let Le=await sv({paths:a,name:U});Le.repaired&&x.push({change:U,reason:Le.reason??"Native confirmed requirements changed"})}let D=await $S([],t),se=D.data&&typeof D.data=="object"&&!Array.isArray(D.data)?D.data:{};return{...D,data:{...se,repaired:!0,repairedPortableTransactions:P,repairedWorkspaceFinishJournals:C,repairedShapeConfirmations:x,repairFindings:N.findings}}}let d=await S9(a),f=new Set(c),p=new Set(l.transactions.filter(N=>N.kind==="migration").map(({change:N})=>N)),h=d.filter(N=>!f.has(N)),[m,v,g,w,k,b,R,y]=await Promise.all([Promise.all(c.map(N=>Ar({paths:a,name:N}))),Promise.all(c.map(N=>QO(a,N))),Promise.all(c.map(N=>vk(a,N))),Promise.all(c.map(async N=>{let P=await O(a,N);return YO(a,N,P)})),Promise.all(c.map(async N=>{let P=await O(a,N);return XO(a,N,P)})),Promise.all(c.map(N=>UO(a,N))),Promise.all(h.map(N=>Of({paths:a,name:N}))),Of({paths:a,projectOnly:!0})]),S=R9([...v.filter(N=>N!==null),...c.flatMap((N,P)=>g[P]&&!p.has(N)?[e0(a,N)]:[]),...w.filter(N=>N!==null),...k.filter(N=>N!==null),...b.filter(N=>N!==null),...l.findings,...o.map(N=>ZO(a,N)),...h.map(N=>({severity:"error",code:"portable-migration-required",message:`Native active change ${N} requires migration to portable Runtime`,path:Df.join(a.changesDir,N,"comet-state.yaml"),repair:"migrate"})),...R.flatMap(({findings:N})=>N),...y.findings]),E={healthy:S.every(N=>N.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:S};return E.healthy?V("doctor",E):kn(E)}let u=await Of({paths:a,...n?{name:n}:{},repair:r,...i?{recoveryStrategy:i}:{}});return u.healthy?V("doctor",u):{command:"doctor",exitCode:65,data:u,error:{code:"invalid-data",message:"Native project needs attention"}}}import{promises as J9}from"fs";import Ce from"path";import i0 from"node:path";async function r0(e=2e3){return process.stdin.isTTY?{text:""}:!Number.isFinite(e)||e<1?{text:null}:process.stdin.readableEnded?{text:""}:await new Promise(t=>{let r=!1,i=0,n=[],a=setTimeout(()=>o({text:null}),Math.ceil(e)),o=d=>{r||(r=!0,clearTimeout(a),process.stdin.removeListener("data",s),process.stdin.removeListener("end",c),process.stdin.removeListener("close",l),process.stdin.removeListener("error",u),process.stdin.pause(),t(d))},s=d=>{let f=Buffer.isBuffer(d)?d:Buffer.from(d),p=1048576-i;if(p<=0){o({text:null});return}let h=f.subarray(0,p);n.push(h),i+=h.length,f.length>h.length&&o({text:null})},c=()=>o({text:Buffer.concat(n,i).toString("utf8")}),l=()=>{process.stdin.readableEnded||o({text:null})},u=()=>o({text:null});process.stdin.on("data",s),process.stdin.once("end",c),process.stdin.once("close",l),process.stdin.once("error",u),a.unref(),process.stdin.resume()})}var A9=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),I9=new Set(["glob","grep","listfiles","read","readfile","search","view"]),n0=["file_path","filePath","path","target_file","targetFile"],a0=["file_paths","filePaths","paths","files","targets"],o0=["operations","edits"],j9=["patch","diff","patchText","patch_text","changes"];function HS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function OS(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function T9(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 $9(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!i0.isAbsolute(r.trim())))return i0.resolve(r.trim())}}function O9(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 D9(e){for(let t of["hook_event_name","hookEventName","event_name","eventName"]){let r=e[t];if(typeof r=="string"&&r.trim())return OS(r)}}function H9(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function F9(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 q9(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return F9(e[t]);return e}function DS(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 Os(e,t){if(typeof t=="string"){let r=t.trim();r&&e.push(r);return}if(Array.isArray(t)){for(let r of t)Os(e,r);return}if(HS(t)){for(let r of n0)Os(e,t[r]);for(let r of a0)Os(e,t[r]);for(let r of o0)Os(e,t[r])}}function L9(e,t){let r=[],i=[t,e].filter(HS);for(let n of i){for(let a of n0)Os(r,n[a]);for(let a of a0)Os(r,n[a]);for(let a of o0)Os(r,n[a]);for(let a of j9){let o=n[a];typeof o=="string"&&r.push(...DS(o))}}return typeof t=="string"&&r.push(...DS(t)),[...new Set(r)]}function Hf(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(wf(e))}catch{let s=DS(e);return s.length>0?{intent:"write",targets:[...new Set(s)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!HS(r))return{intent:"unknown",targets:[],toolName:null};let i=T9(r),n=L9(r,q9(r)),a=$9(r),o=O9(r);if(D9(r)==="beforeagentstart"){let s=H9(r);return{intent:"context",targets:[],toolName:null,...s?{task:s}:{},...a?{cwd:a}:{},...o?{sessionId:o}:{}}}return i&&A9.has(OS(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i&&I9.has(OS(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}:{}}}async function s0(e={}){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Hf("",t);let r=await(e.readStdin??r0)();r.text===null&&(process.stderr.write(`[COMET-HOOK] stdin timeout: the host did not provide hook input within the expected window
|
|
357
|
-
`),process.exit(1));try{return Hf(r.text,t)}catch{return Hf("",t)}}ot();Z();var
|
|
358
|
-
`)}}function
|
|
359
|
-
`),workflow:"native",phase:i.phase,change:i.name}),u.length>0?FS(u):o.length>0&&(c.length>0||l.length>0)?{allowed:!1,reason:"Formal Native requirements must be edited in separate actions from implementation or documentation files",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 Ns({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}:c.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 ea({paths:r,name:i.name,reason:`Observed implementation write before ${c.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:h0(i),workflow:"native",phase:i.phase,change:i.name}:l.length>0?{allowed:!0,reason:"Native neutral document write: documentation edits stay outside the implementation scope and do not return the change to Build",workflow:"native",phase:i.phase,change:i.name}:f?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:p?"Native control artifact write":h?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function Qt(e,t){let r=Ce.relative(e,t);return r===""||!r.startsWith("..")&&!Ce.isAbsolute(r)}async function m0(e){return(await te(e))?.native?.document_writes==="revert"}function v0(e,t){return l0(t,[Ce.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),".comet"])}function g0(e){let t=e.split("/"),r=t[0]==="specs"&&t[1]&&cn.test(t[1])?t[1]:null;return`Native formal Spec artifacts must use ${r?`specs/${r}/spec.md (or specs/${r}/${Ys} for delta metadata)`:`specs/<capability>/spec.md (or specs/<capability>/${Ys} for delta metadata)`}; received ${e}`}function
|
|
350
|
+
`)}import{createHash as jY}from"node:crypto";import{constants as yS,promises as zi}from"node:fs";import js from"node:path";import{TextDecoder as TY}from"node:util";Qc();hi();ei();Z();Ba();Wn();Qc();var tO={"conflict-marker":0,"trailing-whitespace":1,"space-before-tab":2,"scope-mismatch":3,"unsafe-file":4,"binary-skipped":5,"scan-limit":6},ut=class extends Error{constructor(r,i){super(i);this.kind=r}kind};function $Y(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 rO(e){let t=$Y(e.scope.baseline),[r,i]=await Promise.all([aa({changeDir:pe(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),Sc(e.paths,t,{origin:"explicit"})]),n=Kc({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 iO(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 OY(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 DY(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gv(e,t){return e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size&&ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}async function HY(e,t){let r=js.resolve(e),i=js.resolve(t);if(!q(r,i))throw new ut("unsafe-file","Scoped file parent escapes the project root");let n=[],a=r;for(let o of["",...js.relative(r,i).split(js.sep).filter(Boolean)]){o&&(a=js.join(a,o));let s;try{s=await zi.lstat(a)}catch(l){throw l.code==="ENOENT"?new ut("scope-mismatch","Scoped file parent no longer exists"):l}if(!s.isDirectory()||s.isSymbolicLink())throw new ut("unsafe-file","Scoped file parent is not a real directory");let c=await zi.realpath(a);if(n.length>0&&!q(n[0].realPath,c))throw new ut("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 nO(e){for(let t of e){let r;try{r=await zi.lstat(t.path)}catch(i){throw i.code==="ENOENT"?new ut("unsafe-file","Scoped file parent changed while reading"):i}if(!r.isDirectory()||r.isSymbolicLink()||!DY(t,r)||await zi.realpath(t.path)!==t.realPath)throw new ut("unsafe-file","Scoped file parent changed while reading")}}async function FY(e){let t=js.resolve(e.projectRoot,...e.file.path.split("/"));if(!q(e.projectRoot,t))throw new ut("unsafe-file","Scoped file path escapes the project root");let{physicalRoot:r,chain:i}=await HY(e.projectRoot,js.dirname(t)),n;try{n=await zi.lstat(t)}catch(c){throw c.code==="ENOENT"?new ut("scope-mismatch","Scoped file no longer exists"):c}if(!n.isFile()||n.isSymbolicLink())throw new ut("unsafe-file","Scoped file is not a real regular file");if(n.size!==e.file.expected.size)throw new ut("scope-mismatch","Scoped file size no longer matches its projection");let a=await zi.realpath(t);if(!q(r,a))throw new ut("unsafe-file","Scoped file resolves outside the project root");let o=process.platform==="win32"?"r":yS.O_RDONLY|yS.O_NOFOLLOW|yS.O_NONBLOCK,s=await zi.open(t,o).catch(c=>{throw c.code==="ENOENT"?new ut("scope-mismatch","Scoped file no longer exists"):c.code==="ELOOP"||c.code==="ENXIO"?new ut("unsafe-file","Scoped file became unsafe while opening"):c});try{let[c,l,u]=await Promise.all([s.stat(),zi.lstat(t),zi.realpath(t)]);if(await nO(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==a||!Gv(n,c)||!Gv(c,l))throw new ut("unsafe-file","Scoped file changed while opening");let d=[],f=jY("sha256"),p=Buffer.allocUnsafe(64*1024),h=0;for(;;){let k=e.file.expected.size+1-h;if(k<1)throw new ut("scope-mismatch","Scoped file exceeds its projected size");let b=await s.read(p,0,Math.min(p.length,k),null);if(b.bytesRead===0)break;if(h+=b.bytesRead,h>e.file.expected.size)throw new ut("scope-mismatch","Scoped file exceeds its projected size");let R=Buffer.from(p.subarray(0,b.bytesRead));d.push(R),f.update(R)}let[m,v,g]=await Promise.all([s.stat(),zi.lstat(t),zi.realpath(t)]);if(await nO(i),h!==e.file.expected.size||f.digest("hex")!==e.file.expected.hash)throw new ut("scope-mismatch","Scoped file content no longer matches its projection");if(!m.isFile()||!v.isFile()||v.isSymbolicLink()||g!==a||!q(r,g)||!Gv(c,m)||!Gv(c,v))throw new ut("unsafe-file","Scoped file changed while reading");let w=Buffer.concat(d,h);if(w.includes(0))return{bytes:h,text:null};try{return{bytes:h,text:new TY("utf-8",{fatal:!0}).decode(w)}}catch{return{bytes:h,text:null}}}finally{await s.close()}}function qY(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 fs({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 LY(e,t,r){let i=t.split(`
|
|
351
|
+
`);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 MY(e){if(e.state.partial_allowance===null)return new Set;let t=await Gd(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 aO(e){if(!e.state.implementation_scope)throw new Error("Native scoped check requires an implementation scope");let t=await Un(e.paths,e.state.name,e.state.implementation_scope),r=await rO({paths:e.paths,state:e.state,scope:t}),i=iO(e.clock,"start"),n=await MY({paths:e.paths,state:e.state,scope:t}),a=qY(t,n),o=[],s=0,c=E=>(s+=1,o.length>=We.maxIssues?!1:(o.push(E),!0)),l=[],u={files:[],diagnostics:[]},d=0,f=()=>{u.files.length>0&&l.push(u),u={files:[],diagnostics:[]},d=0};for(let E of a.files)(E.expected.size>We.maxFileBytes||u.files.length>0&&(u.files.length>=We.maxFiles||d+E.expected.size>We.maxTotalBytes))&&f(),u.files.push(E),d+=E.expected.size,E.expected.size>We.maxFileBytes&&f();f();let p=[...a.unowned,...a.mismatches].sort((E,N)=>E.localeCompare(N,"en")).map(E=>({path:E,line:1,kind:"scope-mismatch"}));for(let E=0;E<p.length;E+=We.maxFiles)l.push({files:[],diagnostics:p.slice(E,E+We.maxFiles)});let h=l.reduce((E,N)=>E+N.files.length+N.diagnostics.length,0),m=0,v=0,g=0,w=[];for(let E of l){let N={filesSelected:E.files.length+E.diagnostics.length,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0},P=C=>{N.issueCount+=1,c(C)&&(N.recordedIssueCount+=1)};for(let C of E.diagnostics)P(C);for(let C of E.files){if(C.expected.size>We.maxFileBytes){v+=1,N.binaryFilesSkipped+=1;continue}try{let x=await FY({projectRoot:e.paths.projectRoot,file:C});g+=x.bytes,N.bytesScanned+=x.bytes,x.text===null?(v+=1,N.binaryFilesSkipped+=1,P({path:C.path,line:1,kind:"binary-skipped"})):(m+=1,N.filesScanned+=1,LY(C.path,x.text,P))}catch(x){if(!(x instanceof ut))throw x;P({path:C.path,line:1,kind:x.kind})}}w.push(N)}let k=await rO({paths:e.paths,state:e.state,scope:t}),b=iO(e.clock,"end"),R=OY(r,k,t);o.sort((E,N)=>E.path.localeCompare(N.path,"en")||E.line-N.line||tO[E.kind]-tO[N.kind]);let y=hI({change:e.state.name,sourceRevision:e.state.revision,status:s===0&&R.length===0?"passed":"failed",startedAt:i,endedAt:b,contract:{expectedHash:t.scope.contractHash,beforeHash:r.contractHash,afterHash:k.contractHash},implementation:{scopeHash:t.scope.scopeHash,expectedSnapshotHash:t.scope.currentProjectionHash,beforeSnapshotHash:r.snapshotHash,afterSnapshotHash:k.snapshotHash},counts:{filesSelected:h,filesScanned:m,binaryFilesSkipped:v,bytesScanned:g,issueCount:s,recordedIssueCount:o.length,...w.length>1?{batches:w}:{}},issues:o,issuesTruncated:s>o.length,stale:R.length>0,staleReasons:R}),S=await v$({paths:e.paths,name:e.state.name,receipt:y});return{receipt:Gn(y),ref:S}}Fe();async function oO(e){return A(e.paths,`check ${e.name}`,()=>wn(e.paths,e.name,`check ${e.name}`,()=>BY(e)))}async function BY(e){await Ef(e.paths,e.name);let t=await Me(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 y$({paths:e.paths,state:t});if(r)return{change:t,receipt:r.checkReceipt,checkRef:r.checkReceiptRef,ref:r.ref};let i=await aO({paths:e.paths,state:t}),n=await w$({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 sO(e,t){let r=at(e,"change name");$e(e);let{paths:i}=await yr(t);if(await Ae(i,r))throw new I(`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 oO({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}
|
|
352
|
+
`}}import{promises as t0}from"node:fs";import Df from"node:path";fr();import{promises as og}from"fs";import Ot from"path";ot();import{promises as i4}from"fs";Vu();Qe();Z();async function cO(e,t){let r=[],i=Q(e,t.name),n=Ia(i,Lr.stateRef),a;try{a=await At(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=Ia(i,a.trajectoryRef),s=await Cc(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 dr(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=Ia(i,a.checkpointRef);try{let u=await xc(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}Ba();var VY=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function WY(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function zY(e){return e?e.map(WY).join(" "):null}function JY(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 wi(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 GY(e){return e.map(t=>wi(t,[],null))}function KY(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[wi("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(wi("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(wi("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),wi("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(wi("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(wi("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),wi("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Xt(e,t){let r=t.commandArgs===void 0?JY(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?zY(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??GY(t.requiredInputs??[])}}function Kv(e){let r=(e.findings??[]).filter(d=>!_c(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||VY.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 Xt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Xt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[wi("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return Xt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Xt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Xt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Xt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[wi("summary",["--summary"],"<summary>")]});if(n)return Xt(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 Xt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[wi("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Xt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?Xt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Xt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Xt(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"),Xt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[wi("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Xt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Xt(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=KY(e.state);return Xt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import _f from"path";Z();var lO=8,UY={"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 YY(e){let t=UY[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"}:_c(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 XY(e,t,r){if(!r.path)return null;let i;if(_f.isAbsolute(r.path)?i=_f.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=_f.resolve(pe(e,t.name),...r.path.split(/[\\/]/u)):i=_f.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!q(e.projectRoot,i))return null;let n=_f.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function QY(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 NS(e){return e.findings.map(t=>{let r=YY(t.code);return{code:t.code,message:t.message,severity:r.severity,path:XY(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:QY(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 bS(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,lO),truncated:t.length>lO}}var uO=240,dO=8,Uv=50;function fO(e){let t=Array.from(e);return t.length<=uO?e:`${t.slice(0,uO-1).join("")}…`}function ZY(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function e4(e){let t=[...new Set(e.map(ZY))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,dO),reasonCount:e.length,codesTruncated:t.length>dO};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Uv),reasonsTruncated:e.length>Uv}}}async function pO(e){let t=null;try{let s=await go(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:vo(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:vo(e.paths,e.state.name)}}let r=await d$({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=e4(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:Sf.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:fO(r.checkpoint.summary),nextAction:fO(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:Sf.maxArtifacts}}Z();hi();el();Wn();async function t4(e,t){let r=Q(e,t.name),i=await At(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 xc(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 dr(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function r4(e,t){let r=await t4(e,t);return{committed:r,latest:MT(r),history:LT(r)}}async function hO(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await r4(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)}}hi();cr();Z();function Af(e,t){try{return _i(e,t)}catch{return}}var n4=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Qr=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function kS(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function a4(e){return(await uf(e))?.change??null}function o4(e,t,r=!1,i){return Kv({state:e,archiveReady:t,evidenceRetreat:r}).command}async function s4(e,t){let r=pe(e,t.name),i=[...(await pd(r,t.brief)).findings,...(await sA(e,t)).findings,...await cO(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ec(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 im(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 aa({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 na(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 MN(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 xl(e,t,r){let i=await a4(e)===t,n=await ju(e,t),a=await od(e,t),o;try{let N=await di(e,t);if(N.status==="migration-required"&&N.state)return{name:t,artifacts:Af(e,t),phase:N.state.phase,revision:"revision"in N.state?N.state.revision:null,approval:N.state.approval,verificationResult:N.state.verification_result,specChanges:N.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:N.schema,migrationRequired:!0,minimumRuntimeVersion:N.minimumRuntimeVersion,error:N.message};if(N.status!=="current"||!N.state)return{name:t,artifacts:Af(e,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:N.schema,minimumRuntimeVersion:N.minimumRuntimeVersion,error:N.message??`Native change ${t} is incompatible`};o=N.state}catch(N){return{name:t,artifacts:Af(e,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:N.message}}if(n.status!=="available"){let N={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},P=NS({paths:e,state:o,findings:[N]}),C=Kv({state:o,findings:P});return{name:o.name,artifacts:Af(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:C.command,archiveReady:!1,inspection:{freshness:"stale",codes:[N.code],reasonCount:1,codesTruncated:!1},findingSummary:bS(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:C,workspace:a,runtime:n,...r?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:N.message}:{}}}let s=await pO({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await hO(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let N=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:N,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 N=await aa({changeDir:pe(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let D=await vs(e,o.name,o.verification_evidence);for(let se of D.acceptanceTrace.entries)P.set(se.acceptanceId,se.status==="failed"?"failed":se.status==="missing"?"missing":"satisfied")}let C=aC({criteria:N.contract.acceptance,acceptanceHash:N.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),x=C.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",C.nextCursor,"--project-root",e.projectRoot]:null;u={...C,...x?{nextPageCommand:kS(x),nextPageArgs:x}:{}}}catch(N){if(r.acceptanceCursor)throw N;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let N=await Pv(e,o.name,{tolerateInvalidSiblings:!0});d.push(...N.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let N=await Gt(e,o.name);if(N)if(N.schema==="comet.native.workspace.v3"){let P=await sn({paths:e,identity:N});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await za({paths:e,identity:N});f.push(...P.findingCodes.map(C=>({code:C,message:`Native workspace advisory changed: ${C} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let p=[],h=!1;if(o.phase==="verify"){let N=await k$({paths:e,state:o});h=N.freshness!=="fresh",p.push(...N.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,v=[];if(o.phase==="archive")try{m=await qv({paths:e,name:o.name}),v.push(...m.findingCodes.map(N=>({code:N,message:`Native Archive is blocked: ${N}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await s4(e,o),...s.findings,...d,...f,...p,...l,...v].filter((N,P,C)=>C.findIndex(x=>x.code===N.code&&x.path===N.path)===P),w=NS({paths:e,state:o,findings:g}),k=w.filter(N=>!_c(N.code)),b=o.phase==="archive"&&m?.ready===!0&&k.length===0,R=h||o.phase==="archive"&&(m?.findingCodes??[]).some(N=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(N)),y=w.some(N=>N.code==="trajectory-tail-incomplete"||N.code==="trajectory-invalid"||N.requiredAction==="return-to-bound-working-directory"||N.requiredAction==="repair-workspace-binding"),S=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",E=w.find(N=>N.severity==="error");return{name:o.name,artifacts:Af(e,o.name),phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:i,nextCommand:y||S?null:o4(o,b,R,r?.clarificationMode),archiveReady:b,inspection:s.inspection,findingSummary:bS(w),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Kv({state:o,findings:w,archiveReady:b,evidenceRetreat:R,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:Uv,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:w.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...E?{error:E.message}:{}}}async function SS(e){let t;try{t=await qr({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await i4.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Qr.maxChanges))throw new Error(`Native status exceeds ${Qr.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}function Yv(e,t){let r=t.toString(36),i=j("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${r}.${i}`}function c4(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=n4.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=j("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 l4(e,t){let r=await SS(e),i=j("comet.native.status-names.v1",r),n=c4({namesHash:i,total:r.length,cursor:t?.cursor}),a=await Promise.all(r.slice(n,n+Qr.maxItems).map(u=>xl(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?Yv(i,f):null,nextPageCommand:f<r.length?kS(["comet","native","status","--cursor",Yv(i,f)]):null,nextPageArgs:f<r.length?["comet","native","status","--cursor",Yv(i,f)]:null,limits:{...Qr}};if(Buffer.byteLength(JSON.stringify(p),"utf8")>Qr.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?Yv(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?kS(l):null,nextPageArgs:l,limits:{...Qr}}}async function ES(e,t){return(await l4(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}Qc();import{createHash as C4,randomUUID as _4}from"node:crypto";import{constants as _S,promises as Ie}from"node:fs";import Ue from"node:path";ot();hi();Fe();Z();var Zv=Ji(Ri(),1);Oe();import{randomUUID as u4}from"crypto";import{promises as yO}from"fs";import PS from"path";import{isDeepStrictEqual as xS}from"util";ci();Fe();Z();cr();Ba();cc();var Ts=/^[a-f0-9]{64}$/u,d4=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),f4=new Set(["sourceHash","targetHash","nextJournal"]),p4=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),mO=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),h4=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Xv(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function vO(e){return JSON.stringify(e,null,2)+`
|
|
353
|
+
`}function CS(e){return e.schema===st?qu(e):$n(e)}function RS(e,t){return{...e,schema:st,minimum_runtime_version:2,revision:t}}function m4(e){return{...e,schema:jn,minimum_runtime_version:2,revision:1,previousState:RS(e.previousState,1),nextState:RS(e.nextState,2)}}function Qv(e,t){let r=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:it,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 v4(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?ae(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:ja,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:r,previousState:Qv(e.previousState),nextState:{...Qv(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:r},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:vn.definition.metadata.version,skillHash:Nf}:e.nextRun}}function gO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Cl(e,t){return JSON.stringify(qu(e))===JSON.stringify(qu(t))}function wO(e,t){return JSON.stringify($n(e))===JSON.stringify($n(t))}function sa(e,t){return xS(e,t)}function g4(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(Xv(n,p4,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!Ts.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"||!Ts.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Wa(n.previousRun),o=Wa(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||!sa(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!==mO.size||u.some(f=>!mO.has(f))||l.fromSchema!==st||l.toSchema!==it||!["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=ae(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 If(e,t){return PS.join(Q(e,t),"schema-migration.json")}function w4(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Xv(e,d4,"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===nr&&r.toSchema===st,n=r.fromSchema===st&&r.toSchema===it;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"||!Ts.test(r.sourceHash)||typeof r.targetHash!="string"||!Ts.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?Ii(r.nextState):zt(r.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(ae((0,Zv.stringify)(CS(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");Xv(r.transition,f4,"Schema migration transition target");let l=r.transition;if(typeof l.sourceHash!="string"||!Ts.test(l.sourceHash)||typeof l.targetHash!="string"||!Ts.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=i?Gk(l.nextJournal,t):Jk(l.nextJournal,t);if(ae(JSON.stringify(l.nextJournal,null,2)+`
|
|
354
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(i&&a.schema===st?Cl(a,u.previousState)||Cl(a,u.nextState):a.schema===it&&(wO(a,u.previousState)||wO(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!==it)throw new Error("Schema migration transition supersede target schema is invalid");s=g4(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");Xv(r.runRetreat,h4,"Schema migration Run retreat");let l=r.runRetreat,u,d;try{u=Wa(l.previousRun),d=Wa(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!Ts.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!==it||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 jf(e,t){let r=If(e,t),i=B(e,r);await T(i,r);try{let n=await Vh({root:i,file:r,maxBytes:null,label:"Native schema migration journal"});return w4(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function y4(e,t,r){let i=await Ec(e,t),n=i?await im(e,i):await nm(e,{now:new Date(r),origin:"legacy-migration"});if(!n.complete){let a=yN(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 jc(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}i===null&&await NN(e,t,n)}async function NO(e){try{return await si(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function N4(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 bO(e,t){let r=t.transitionSupersede,i=Q(e,t.change),n=await dr(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&&!xS(o.event,N4(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 b4(e,t,r){if(!t.transitionSupersede)return;let i=Yt(e,t.change),n=await NO(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=Q(e,t.change),o=await At(a),s=await bO(e,t),c=await xc(a,t.transitionSupersede.nextRun.checkpointRef);if(!r||!o||!sa(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!==ae(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function k4(e,t,r){let i=t.transitionSupersede;if(!i)return;let n=Q(e,t.change),a=await At(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!sa(a,i.nextRun)){if(!sa(a,i.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rs(n,i.nextRun),await r?.afterRunStateWritten?.(t)}if(!sa(await At(n),i.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await bO(e,t);if(o.sequence===null){let l=await ho({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 As({changeDir:n,run:i.nextRun,trajectoryOffset:o.sequence,evidenceHash:i.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t);let s=Yt(e,t.change),c=await NO(s);if(c!==null){if(c!==i.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await yO.rm(s),await r?.afterTransitionSuperseded?.(t)}}async function S4(e,t,r){if(!t.runRetreat)return;let i=Q(e,t.change),n=await At(i);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!sa(n,t.runRetreat.nextRun)){if(!sa(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await rs(i,t.runRetreat.nextRun),await r?.afterRunStateWritten?.(t)}let a=await dr(i,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await ho({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 As({changeDir:i,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t)}async function E4(e,t,r){let i=await jf(e,t);if(!i)return null;if(await $c(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=PS.join(pe(e,t),ct),a=await si(n);if(await b4(e,i,a===i.targetHash),await y4(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 Ne(n,(0,Zv.stringify)(CS(i.nextState))),await r?.afterStateWritten?.(i)}if(i.transition){let o=Yt(e,t),s=await si(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 ve(o,i.transition.nextJournal),await r?.afterTransitionWritten?.(i)}}return await k4(e,i,r),await S4(e,i,r),await yO.rm(If(e,t),{force:!0}),i.nextState}async function R4(e){let t=Q(e.paths,e.state.name),r=await At(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=ae(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:r,nextRun:i,evidenceHash:n,eventData:{fromSchema:st,toSchema:it,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function P4(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=Cl(r,t.previousState),a=Cl(r,t.nextState);if(!n&&!a)throw new Error(`Native change ${r.name} does not match its v2 evidence transition`);let o=Q(e.paths,r.name),s=await At(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${r.name}`);let c=t.previousRun!==null&&sa(s,t.previousRun),l=sa(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 dr(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(!xS(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let p={...Qv(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},h=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=ae(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 si(Yt(e.paths,r.name)),transitionId:t.id,previousRun:h,nextRun:m,evidenceHash:v,eventData:{fromSchema:st,toSchema:it,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function x4(e){let t,r,i,n;if(e.state.schema===nr){if(t=RS(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==Jo)throw new Error("Native v1 change has a transition from another schema generation");let s=m4(e.pendingTransition.journal);if(gO(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(gO(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=Yt(e.paths,e.name);r={sourceHash:await si(c),targetHash:ae(vO(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==jn)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 P4({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,i=l.plan}else{let l=v4(s);if(Cl(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Cl(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=Yt(e.paths,e.name);r={sourceHash:await si(u),targetHash:ae(vO(l)),nextJournal:l}}}else t=Qv(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await R4({paths:e.paths,state:e.state,migrationId:e.id}));let a=PS.join(pe(e.paths,e.name),ct),o=(0,Zv.stringify)(CS(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===nr?st:it,sourceHash:await si(a),targetHash:ae(o),createdAt:e.now.toISOString(),nextState:t,...r?{transition:r}:{},...i?{transitionSupersede:i}:{},...n?{runRetreat:n}:{}}}async function kO(e){return A(e.paths,`migrate schema for ${e.name}`,()=>wn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let r=await E4(e.paths,e.name,e.hooks);if(r?.schema===it)return r;let i=await di(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 $c(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!==nr&&n.schema!==st)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Kk(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 x4({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??u4()}),s=If(e.paths,e.name),c=B(e.paths,s);await T(c,s),await ve(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}es();ei();Wn();Md();el();var ca=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),$s=/^([a-f0-9]{64})\.json$/u,A4=/^\.([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,I4=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,eg=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function IS(e,t){return ne({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bn(e,t){return IS(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xO(e,t){return IS(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function _l(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Nr(e,t){return e<t?-1:e>t?1:0}function j4(e,t){let r=Ue.relative(e.projectRoot,t);if(r.length===0||Ue.isAbsolute(r)||r===".."||r.startsWith(`..${Ue.sep}`))throw new Error("Native evidence retention finding path is outside the project");return r.split(Ue.sep).join("/")}function CO(e,t){return Ue.join(Q(e,t),"evidence")}function tg(e,t){return j4(e,CO(e,t))}async function rg(e,t){let r=Ue.resolve(e),i=Ue.resolve(t);if(!q(r,i))throw new Error("Native evidence retention path escapes its managed change");let n=Ue.relative(r,i).split(Ue.sep).filter(Boolean),a=[],o=r;for(let s of["",...n]){s&&(o=Ue.join(o,s));let c=await Ie.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Ie.realpath(o);if(a.length>0&&!q(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,..._l(c)})}return a}async function yi(e){for(let t of e){let r=await Ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!IS(t,r)||await Ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function _O(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:Fi(e,t)}function SO(e){return e!==null&&I4.test(e)?[e]:[]}function T4(e,t,r,i){if(e==="snapshots")return{canonical:Gc(r,t),dependencies:[]};if(e==="scopes"){let a=Uc(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=Wm(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=Ld(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(SO));return{canonical:a,dependencies:[a.implementationScopeRef,vb(a.reportHash),...SO(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"||C4("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=Wd(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=Gn(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 bo(e){let t=await Ie.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let r=e.kind==="check-receipts"?null:pi;if(r!==null&&t.size>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let i=await Ie.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":_S.O_RDONLY|_S.O_NOFOLLOW|_S.O_NONBLOCK,a=await Ie.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(),Ie.lstat(e.file),Ie.realpath(e.file)]);if(await yi(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==i||!bn(_l(t),o)||!bn(_l(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===null?u.length:r+1-d,k=await a.read(u,0,Math.min(u.length,w),null);if(k.bytesRead===0)break;if(d+=k.bytesRead,r!==null&&d>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,k.bytesRead)))}let[f,p,h]=await Promise.all([a.stat(),Ie.lstat(e.file),Ie.realpath(e.file)]);if(await yi(e.directoryChain),!p.isFile()||p.isSymbolicLink()||h!==i||!bn(_l(o),f)||!bn(_l(o),p))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(m)}catch(w){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:w})}let g=T4(e.kind,e.hash,v,e.name);if(m!==JSON.stringify(g.canonical,null,2)+`
|
|
355
|
+
`)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:_l(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(Nr)}}finally{await a.close()}}async function EO(e){try{return await Ie.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function $4(e){let t=Q(e.paths,e.name),r=t,i=CO(e.paths,e.name);await T(B(e.paths,i),i);let n;try{let s=await rg(t,i);n=await Ie.readdir(i,{withFileTypes:!0}),await yi(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of eg){if(!n.some(f=>f.name===s))continue;let c=Ue.join(i,s),l=await rg(t,c),u=(await Ie.readdir(c,{withFileTypes:!0})).sort((f,p)=>Nr(f.name,p.name)),d=new Map;for(let f of u){let p=A4.exec(f.name);if(!p)continue;let h=d.get(p[1])??[];h.push(f),d.set(p[1],h)}for(let[f,p]of[...d.entries()].sort(([h],[m])=>Nr(h,m))){if(p.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let h=p[0];if(!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${h.name}`);let m=Ue.join(c,f),v=$s.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${h.name}`);let g=_O(s,v),w=Ue.join(c,h.name),k=await bo({changeRoot:r,file:w,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),b=await EO(m),R=b?null:await bo({changeRoot:r,file:m,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:m,quarantine:w,document:k,action:b?"restore-original":"finish-linked-recovery",originalDocument:R})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(Nr);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Al(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${ig(o)}`),path:tg(e.paths,e.name)}]};for(let s of a.sort((c,l)=>Nr(c.ref,l.ref))){if(await yi(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await bo({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await bo({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!bn(s.originalDocument.identity,d.identity)||!bn(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Ie.rm(s.quarantine),await yi(s.document.directoryChain);continue}if(!await EO(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Ie.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!bn(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Ie.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await bo({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await bo({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:$s.exec(Ue.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!xO(s.document.identity,l.identity)||!bn(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Ie.rm(s.quarantine),await yi(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Al(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${ig(o)}`),path:tg(e.paths,e.name)}]}}async function O4(e,t){let r=Q(e,t),i=r,n=Ue.join(r,"evidence");await T(B(e,n),n);let a;try{let l=await rg(r,n);a=await Ie.readdir(n,{withFileTypes:!0}),await yi(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!eg.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(Nr);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${ig(o)}`);let s=[],c=0;for(let l of eg){if(!a.some(p=>p.name===l))continue;let u=Ue.join(n,l),d=await rg(i,u),f=(await Ie.readdir(u,{withFileTypes:!0})).sort((p,h)=>Nr(p.name,h.name));await yi(d);for(let p of f){if(s.length>=ca.maxDocuments)throw new Error(`Native evidence store exceeds ${ca.maxDocuments} documents`);let h=$s.exec(p.name);if(!h||!p.isFile()||p.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${p.name}`);let m=_O(l,h[1]),v=Ue.join(u,p.name);await T(B(e,v),v);let g=await bo({changeRoot:i,file:v,ref:m,kind:l,hash:h[1],name:t,directoryChain:d});if(c+=g.size,c>ca.maxScannedBytes)throw new Error(`Native evidence store exceeds ${ca.maxScannedBytes} scanned bytes`);s.push(g)}await yi(d)}return s}function RO(e,t){let r=new Set,i=[...e].sort(Nr).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(Nr).reverse())r.has(o)||i.push(o)}return r}function D4(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(Nr),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(Nr))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function H4(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=RO(t,i),a=new Set(n);for(let c of e)r-c.mtimeMs<ca.minimumAgeMs&&a.add(c.ref);for(let c of eg){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||Nr(u.ref,d.ref)).slice(0,ca.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=RO(a,i),s=e.filter(c=>!o.has(c.ref)&&r-c.mtimeMs>=ca.minimumAgeMs).sort((c,l)=>Nr(c.ref,l.ref));return{candidates:D4(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function ig(e){let t=e.slice(0,ca.maxReportedRefs),r=e.length-t.length;return`${t.join(", ")}${r>0?`, ... (${r} more)`:""}`}function Al(e){let t=ca.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 AS(e,t,r,i){let n=t.candidates.map(a=>a.ref).sort(Nr);return{severity:"info",code:r?"evidence-retention-cleaned":"evidence-retention-candidates",message:Al(`${r?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${ig(n)}`),path:i}}async function PO(e,t){try{await Ie.lstat(t);return}catch(r){if(r.code!=="ENOENT")return}try{await Ie.rename(e,t)}catch{}}async function F4(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await yi(e.directoryChain);let r=await bo({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:$s.exec(Ue.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),i=await Ie.lstat(e.file),n=await Ie.realpath(e.file);if(!i.isFile()||i.isSymbolicLink()||!bn(e.identity,i)||!bn(e.identity,r.identity)||!q(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=Ue.join(Ue.dirname(e.file),`.${Ue.basename(e.file)}.${_4()}.gc`);await Ie.rename(e.file,a);try{let[o,s]=await Promise.all([Ie.lstat(a),Ie.realpath(a)]);if(await yi(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!xO(e.identity,o)||!q(e.directoryChain[0].realPath,s))throw await PO(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Ie.rm(a),await yi(e.directoryChain)}catch(o){throw await PO(a,e.file),o}}async function q4(e){if((await te(e.projectRoot))?.native.pending_root_move)return!0;let r;try{r=await Ie.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 Rr(e,i.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function L4(e,t){if(t)return[t];let r;try{r=await Ie.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(Nr)}async function M4(e,t){let r=await di(e,t);if(r.status!=="current"||!r.state||r.state.archived)return!0;let[i,n,a]=await Promise.all([na(e,t),jf(e,t),go(e,t)]);return i!==null||n!==null||a!==null}async function B4(e){if(await M4(e.paths,e.name))return[];let t=await di(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let r=await $4({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 O4(e.paths,e.name),a=H4(n,i,e.nowMs);if(a.candidates.length===0)return r.findings;let o=tg(e.paths,e.name);if(!e.repair)return[...r.findings,AS(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await F4(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...r.findings,...s.length>0?[AS(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Al(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...r.findings,AS(e.name,a,!0,o)]}async function AO(e){if(e.deferAll||await q4(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 L4(e.paths,e.name))try{a.push(...await B4({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Al(`Native evidence retention refused to clean ${o}: ${s.message}`),path:tg(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 A(e.paths,"prune Native evidence",()=>r(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Al(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}zo();Z();cr();Oe();ot();zo();Z();cr();es();import{createHash as V4,randomUUID as W4}from"crypto";import{promises as ko}from"fs";import De from"path";async function $t(e){try{return await ko.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function z4(e){let t;try{t=await ko.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 Rr(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 J4(e,t){for(let r of await ko.readdir(e.locksDir,{withFileTypes:!0})){let i=De.join(e.locksDir,r.name);if(De.resolve(i)!==De.resolve(t)&&(r.isFile()||r.isSymbolicLink()))throw new Error(`Native lock must be diagnosed before moving the root: ${i}`)}}async function G4(e){let t;try{t=await ko.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 Gt(e,r.name);if(i){await vm({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 K4(e){let t;try{t=await ko.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 Gt(e,r.name);if(i?.schema==="comet.native.workspace.v3"){let n=await sn({paths:e,identity:i});if(n.state!=="aligned")throw new Error(n.message??"workspace binding is not aligned")}else if(i){let n=await za({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 $f(e,t){let r=[];async function i(n){let a=await Er({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=De.join(n,s.name);if(t.excludedFiles?.has(De.resolve(c))){await a.verify();continue}let l=await ko.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:De.relative(e,c).split(De.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await Qo({root:e,file:c,label:`Native root file ${De.relative(e,c)}`});r.push({ref:De.relative(e,c).split(De.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 U4(e,t,r,i){await nn({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await Er({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=De.join(a,l.name);if(De.resolve(u)===De.resolve(r)){await s.verify();continue}let d=await ko.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=De.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await nn({root:i,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Ha({sourceRoot:e,source:u,targetRoot:i,target:f,maxBytes:null,label:`Native root move file ${De.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 Il(e,t,r,i){let n=await $f(e,{rejectSymlinks:!0,excludedFiles:r?new Set([De.resolve(r)]):void 0}),a=await $f(t,{rejectSymlinks:!0,excludedFiles:i?new Set([De.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 $O(e,t){return De.join(e.artifactRoot,`.comet-native-move-${t}`)}function Y4(e,t){return De.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function X4(e){return`${e}.removing`}function IO(e,t){return De.join(De.dirname(e),`.${De.basename(e)}.${t}.rollback-removing`)}function OO(e,t,r){return De.join(Uh(e,t).directory,`root-move-cleanup-${r}.json`)}function Q4(e){return JSON.stringify(e,null,2)+`
|
|
356
|
+
`}function Z4(e){return V4("sha256").update(e).digest("hex")}function e9(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("\\")||De.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 t9(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(e9);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=De.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 r9(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=Q4(t);return await Ne(OO(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),Z4(r)}async function i9(e){let t=await ht({root:e.paths.runtimeDir,file:OO(e.paths,e.id,e.cleanup.kind),maxBytes:null,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 t9(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function jS(e){let t=await $f(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 jO(e){return e.ref.split("/").length}async function n9(e){let r=[...await jS({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>jO(a)-jO(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=De.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Wh({root:e.projectRoot,file:a,maxBytes:null,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await nN({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 jS({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await nN({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function ng(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function DO(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 a9(e,t,r,i){for(let a of[e,t])try{let o=await Rr(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=De.join(r,"runtime","transactions",i,"transaction.json");try{let a=await ht({root:r,file:n,maxBytes:null,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 TO(e){let t=ng(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Dr(e.projectRoot,t),t}async function Tf(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=ng(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 Dr(e.projectRoot,r),r}async function ag(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 $t(e.target),a=await $t(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 r9({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await $f(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Tf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await i9({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await $t(e.target),a=await $t(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 EC({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 Tf({projectRoot:e.projectRoot,config:t,id:e.id})}return await jS({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Tf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Tf({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await n9({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Tf({projectRoot:e.projectRoot,config:t,id:e.id})}async function HO(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await $t(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=X4(e.staging);t=await ag({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 $f(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([De.resolve(e.lockFile)])}),await U4(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Il(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await TO({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await $t(e.destinationPaths.nativeRoot)){if(await $t(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Il(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await $t(e.staging))throw new Error("Native move staging tree is missing");await Il(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await ko.rename(e.staging,e.destinationPaths.nativeRoot)}t=await TO({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 $t(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=Y4(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await $t(e.sourcePaths.nativeRoot)&&await Il(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await ag({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 G4(e.destinationPaths);let n=await Rr(e.destinationPaths,e.pending.id);await gc(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 Dr(e.projectRoot,o),o}async function FO(e){let t=await te(e.projectRoot)??Mo("docs");if(t.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is already incomplete`);let r=Aa(e.toArtifactRoot);if(r===t.native.artifact_root)throw new Error(`Native artifact root is already ${r}`);let i=await Se(e.projectRoot,t.native.artifact_root),n=await Se(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 $t(i.nativeRoot))throw new Error(`Native source root does not exist: ${i.nativeRoot}`);if(await z4(i),await $t(n.nativeRoot))throw new Error(`Native destination is occupied: ${n.nativeRoot}`);let a=await An(i,"root-move",`move root to ${r}`),o=W4(),s={id:o,fromArtifactRoot:t.native.artifact_root,toArtifactRoot:r,stage:"copying"},c=DO({id:o,paths:i,now:e.now??new Date}),l=$O(n,o);try{if(await J4(i,a.file),await K4(i),await $t(l))throw new Error(`Native move staging path is occupied: ${l}`);return await Dr(e.projectRoot,ng(t,s)),await uN(i,c),await e.hooks?.afterRootMoveStage?.("copying",c),await HO({projectRoot:e.projectRoot,config:ng(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 In(a)}}async function qO(e){let t=await te(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let i=await Se(e.projectRoot,r.fromArtifactRoot),n=await Se(e.projectRoot,r.toArtifactRoot),a=$O(n,r.id),o=await $t(i.nativeRoot)?i:n,s=await An(o,"root-move",`recover root ${r.id}`);try{let c;try{c=await a9(i,n,a,r.id)}catch(h){if(r.stage!=="copying"||!await $t(i.nativeRoot))throw h;let m=DO({id:r.id,paths:i,now:new Date});await uN(i,m),c={journal:m,paths:i}}if(e.strategy==="continue"){let h=await HO({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:h}}if(!await $t(i.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=IO(n.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await $t(n.nativeRoot)&&await Il(i.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await ag({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=IO(a,r.id);!t.native.pending_root_move?.cleanup&&await $t(a)&&await Il(i.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await ag({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 Rr(i,r.id);await Yh(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 Dr(e.projectRoot,p),{activeNativeRoot:i.nativeRoot,config:p}}finally{await In(s)}}es();var jl=4096,o9=4096,s9=1024;async function So(e,t,r){try{let i=await Er({root:B(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 sg(e,t){let r=new Map(e.map(i=>[Ot.resolve(i.file),{...i,file:Ot.resolve(i.file)}]));for(let{paths:i,file:n}of r.values()){let a;try{a=await Du(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 Wo(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}if(a.status==="unknown"){let o=await Wo(i,n,a,{allowAgedUnknown:!0});if(o.status==="removed"){t.push({severity:"info",code:"aged-unknown-recovery-lock-removed",message:"Removed a recovery lock whose owner could not be proven stale and was recorded over fifteen minutes ago",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"||a.status==="unknown"?(t.push({severity:"error",code:"lock-owner-unknown",message:"Native recovery lock owner cannot be proven stale; retry doctor --repair after the lock is older than fifteen minutes",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 c9(e,t){let r=df(e),i;try{await T(e.projectRoot,r);let n=await uf(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 Ae(e,i.change)?[]:(await Me(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 og.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 l9(e){let t=[];for(let r of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(B(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 u9(e,t){let r=[],i=[];for(let n of await So(e,e.transactionsDir,o9)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await Rr(e,n.name)}catch(o){r.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ot.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 Vo([e],`doctor archive recovery ${a.id}`,async()=>await sg([{paths:e,file:Ot.join(e.locksDir,"root-move.lock")},{paths:e,file:Ot.join(e.locksDir,"archive.lock")}],r)?(await M$({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 d9(e,t,r){let i=[];for(let n of await So(e,e.locksDir,s9)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ot.join(e.locksDir,n.name);try{let o=await Du(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"){let s=qy(o.owner);if(t&&s>=Ou&&r.length===0){let c=await Wo(e,a,o,{allowAgedUnknown:!0});if(c.status==="removed"){i.push({severity:"info",code:"aged-unknown-lock-removed",message:"Removed a Native lock whose owner could not be proven stale and was recorded over fifteen minutes ago",path:a});continue}if(c.status==="missing")continue;i.push({severity:"warning",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing takeover",path:a});continue}i.push({severity:"warning",code:"lock-owner-unknown",message:s>=Ou?"Native lock owner cannot be proven stale; run doctor --repair to take over this lock":`Native lock owner cannot be proven stale yet; retry doctor --repair after ${Math.ceil((Ou-s)/6e4)} more minutes`,path:a})}else if(o.status==="stale")if(t&&r.length===0){let s=await Wo(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 f9(e,t,r=5){let i=[],n=t?await ES(e,{maxVerifyFailures:r}).then(a=>a.filter(o=>o.name===t)):await ES(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:Ot.join(e.changesDir,a.name,ct)});continue}let o=await xl(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:Ot.join(e.projectRoot,s.path)}:{}})}return i}async function p9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{let a=await Cc(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 x_(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:Ot.join(Q(e,n),"trajectory.jsonl")})}return r}async function h9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=await ju(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=Lo(e,n),s=je(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 Vo([e],`migrate Runtime layout for ${n}`,async()=>{let c=await qr({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await og.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await qr({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await og.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 og.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 m9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{if(!await jN(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:Ac(e,n),repair:"migrate"});continue}let a=await Me(e,n);await H_({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:Ac(e,n)})}catch(a){r.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:Ac(e,n)})}return r}async function v9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=If(e,n);try{let o=await jf(e,n),s=await di(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:Ot.join(e.changesDir,n,ct)});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:Ot.join(e.changesDir,n,ct),repair:"migrate"});continue}await kO({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:Ot.join(e.changesDir,n,ct)})}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 g9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a;try{a=await na(e,n)}catch(o){if(o instanceof bf)continue;r.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Yt(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await Vo([e],`doctor transition recovery ${n}`,async()=>await sg([{paths:e,file:Ot.join(e.locksDir,"root-move.lock")},{paths:e,file:Ot.join(e.locksDir,`transition-${n}.lock`)}],r)?(await t$(e,n),!0):!1))continue;r.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Yt(e,n)})}catch(o){r.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Yt(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:Yt(e,n),repair:"continue"})}}return r}async function w9(e,t){let r=[],i=t.name?[t.name]:(await So(e,e.changesDir,jl)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=vo(e,n),o;try{o=await go(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 Vo([e],`doctor checkpoint recovery ${n}`,async()=>await sg([{paths:e,file:Ot.join(e.locksDir,"root-move.lock")},{paths:e,file:Ot.join(e.locksDir,`transition-${n}.lock`)}],r)?(await f$(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 Of(e){let t=e.repair??!1,r=[],i=e.paths,n;try{n=await te(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([Se(i.projectRoot,c.fromArtifactRoot),Se(i.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await sg([{paths:l,file:Ot.join(l.locksDir,"root-move.lock")},{paths:u,file:Ot.join(u.locksDir,"root-move.lock")}],r))return{healthy:!1,findings:r};let f=await qO({projectRoot:i.projectRoot,strategy:e.recoveryStrategy});i=await Se(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 l9(i);if(r.push(...o),o.length>0)return{healthy:!1,findings:r};let s=await u9(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return r.push(...s.findings),e.projectOnly||(r.push(...await h9(i,{name:e.name,repair:t})),r.push(...await v9(i,{name:e.name,repair:t})),r.push(...await m9(i,{name:e.name,repair:t})),r.push(...await p9(i,{name:e.name,repair:t})),r.push(...await g9(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),r.push(...await w9(i,{name:e.name,repair:t})),r.push(...await AO({paths:i,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),r.push(...await d9(i,t,s.unfinished)),r.push(...await c9(i,t)),e.projectOnly||r.push(...await f9(i,e.name,n?.native.max_verify_failures??5)),{healthy:r.every(c=>c.severity==="info"),findings:r}}sr();ln();Ya();Fe();import{promises as BO}from"node:fs";import VO from"node:path";import LO from"node:path";function MO(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function kt(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:MO(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:MO(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=>LO.relative(t.projectRoot,LO.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}Z();function WO(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function zO(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 JO(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:b9(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:k9(i,r)}))]:[]]}function GO(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 y9(e,t){let r=t?.execution;if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running")return;let i=r.verifierStartedAt??null,n=i!==null||r.requestCheckRounds>0;return{attempt:e.loop.attempt,registeredAt:r.startedAt,confirmedAt:i,confirmation:n?"confirmed":"unconfirmed",...n?{}:{waitingMinutes:Math.max(0,Math.round((Date.now()-Date.parse(r.startedAt))/6e4))}}}function cg(e,t,r=ie(e.projectRoot)){let 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:VO.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 TS(e){let{state:t,paths:r}=e,i=e.finishJournal??null,n=kt(t),a=i!==null,o=i?.result?.message??"Native Archive completed, but workspace finish is still pending; retry the recorded finish command.",s=a?{...L(t),disposition:"blocked",action:"archive",commandArgs:i?.result?.recoveryArgs??["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],inputOptions:[],userCommunication:{required:!0,message:o,suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the reported Git blocker; do not treat this archived change as complete until it succeeds."},runnerAction:{...L(t).runnerAction,kind:"none"}}:L(t),c=e.details?JO(t,null,[]):[],l=zO(e.cursor,t.state_version,0),u=c.slice(l,l+32),d=l+u.length<c.length?WO(t.state_version,0,l+u.length):null;return{schema:"comet.native.status.v2",name:t.name,artifacts:_i(r,t.name),phase:t.phase,status:a?"blocked":t.status,stateVersion:t.state_version,archived:!0,archiveRef:VO.relative(r.projectRoot,e.file).replaceAll("\\","/"),loop:t.loop,acceptance:GO(t),unresolvedAcceptanceIds:n.unresolved_acceptance_ids,verificationResult:t.verification_result,blockers:a?[...n.blockers,{owner:"runtime",reason:o,acceptance_ids:[],resolution_action:"wait-external"}]:n.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:s,...e.details?{details:{stateVersion:t.state_version,items:u,nextCursor:d,nextPageArgs:d?["comet","native","status",t.name,"--details","--cursor",d,"--project-root",r.projectRoot,"--json"]:null}}:{}}}function N9(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 lg(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function b9(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:lg(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function k9(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:lg(e.summary,t)??""}}async function Ar(e){let t=await ns(e),r=kt(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await nt({paths:e.paths,state:t.state}),a=await mn({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await J(e.paths,e.name,{diagnostics:!0}),s=o?{...cg(e.paths,t.state,e.gitContext),projectRoot:"."}:cg(e.paths,t.state,e.gitContext),c=L(t.state,n,{verifierExecutionRef:qc(t.state,t.local),...t.local?{verificationCheckPlans:dl(t.local,t.local.workspace.projectRoot)}:{}}),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?N9(e.paths,o):[],d=o?(()=>{let h=new Map(n?.children.map(y=>[y.name,y.status])??[]),m=y=>h.get(y.name)??y.status,v=o.children.filter(y=>m(y)==="pending"||m(y)==="ready").length,g=o.children.filter(y=>m(y)==="active"||m(y)==="verified").length,w=o.children.filter(y=>m(y)==="integrated"||m(y)==="archived").length,k=o.children.filter(y=>m(y)==="blocked"||m(y)==="needs-reverify").length,b=o.children.filter(y=>m(y)==="active"||m(y)==="blocked"||m(y)==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:lg(y.blocker,u)})),R=o.children.flatMap(({blocker:y})=>{let S=lg(y,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:v,working:g,integrated:w,blocked:k,active:b,agents:{working:o.children.filter(({task:y})=>y!==null).length,completed:w},risks:R,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&w===o.children.length?"parent-verification":v>0?"dispatch-ready-child":k>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let h=o?.stateVersion??0,m=JO(t.state,o,u),v=zO(e.cursor,t.state.state_version,h),g=m.slice(v,v+32),w=v+g.length<m.length?WO(t.state.state_version,h,v+g.length):null;return{items:g,nextCursor:w,supervisorStateVersion:h}})():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,artifacts:_i(e.paths,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:GO(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:(()=>{let h=y9(t.state,t.localStatus==="available"?t.local:null);return{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null,...h?{verifierStartup:h}:{}}})(),...n?{childSummary:n.children.reduce((h,m)=>({...h,[m.status]:(h[m.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 KO(e){let t;try{t=await BO.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 BO.readFile(`${X(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"))}Xo();var S9=1800*1e3;async function la(e,t){let r=await nt({paths:e,state:t});return L(t,r)}async function UO(e,t){let r;try{r=await lt(G(e,t))}catch{return null}if(r?.execution?.stage!=="checking"||r.execution.actor!=="runtime"||r.execution.status!=="running")return null;let i=await ul(r);if(i==="running")return null;let n=i==="orphaned"?`Native Runtime check operation ${r.execution.operationId} has no live owner or active check process`:`Native Runtime check operation ${r.execution.operationId} is running, but its owner process identity is unavailable`;return{severity:"error",code:"portable-check-execution-stuck",message:`${t}: ${n}; run comet native doctor ${t} --repair to recover it`,path:G(e,t),repair:"recover"}}async function YO(e,t,r){if(r.phase!=="shape"||r.status!=="await-user"||r.loop.next_action!=="confirm-shape")return null;let i=await Mi({paths:e,state:r});if(!i.drifted)return null;let n=i.reason??"Native confirmed requirements changed";return{severity:"error",code:"portable-shape-confirmation-drift",message:`${t}: pending Shape confirmation is stale (${n}); run comet native doctor ${t} --repair to reopen Shape`,path:gt(e,t),repair:"recover",repairCommand:`comet native doctor ${t} --repair`}}async function XO(e,t,r){if(r.archived||r.workspace.change_branch!==null)return null;let i;try{i=await It({changeDir:X(e,t),policy:"advisory"})!==null}catch{i=!0}if(!i)return null;let n=ie(e.projectRoot),a=n.isGitWorktree&&n.currentBranch!==null&&er(e.projectRoot,n.currentBranch)!==null,o=a&&Oc(e.projectRoot),s=a?await QN(e,t):[];return{severity:"error",code:"portable-supervisor-git-binding-missing",message:a?o?s.length>0?`${t}: the Supervisor change has no Git branch binding while active child tasks exist (${s.join(", ")}); finish or recover those tasks before rerunning the latest continuation`:`${t}: the Supervisor change has no Git branch binding; run comet native status ${t} --json and rerun its continuation to bind branch ${n.currentBranch} at the Shape confirmation boundary`:`${t}: the Supervisor change has no Git branch binding and the current Git baseline is dirty; commit or stash pending changes to restore a clean current working directory, then rerun the latest continuation`:`${t}: the Supervisor change requires Git; initialize a Git repository, commit to a branch, then rerun the latest continuation`,path:gt(e,t)}}async function E9(e){let t;try{t=await t0.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 R9(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function QO(e,t){let r;try{r=await t0.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}-${R9(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:Df.join(e.archiveDir,n.name)}:null}function P9(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()]}async function x9(e,t){let r=[];if(t!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))return r;let i=(n,a)=>r.push({name:n,message:a});return t!==void 0?await ta(e,t,{onError:i}):await kv(e,{onError:i}),r}function ZO(e,t){return{severity:"error",code:"portable-workspace-finish-journal-invalid",message:`Native workspace finish journal for ${t.name} is invalid (${t.message}); run comet native doctor ${t.name} --repair to quarantine it and resume from the preserved change or Archive record`,path:Df.join(e.transactionsDir,`workspace-finish-${t.name}.json`),repair:"continue",repairCommand:`comet native doctor ${t.name} --repair`}}function kn(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function e0(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:Df.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function C9(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}function _9(e,t,r){let i=new Map(t.children.map(({name:a,status:o})=>[a,o]));return{severity:"error",code:"portable-supervisor-ready-dependencies-unmet",message:`Native Supervisor children are marked ready but their dependencies are not integrated: ${r.map(a=>{let o=a.dependsOn.filter(s=>i.get(s)!=="integrated");return`${a.name} (waiting on: ${o.join(", ")})`}).join("; ")}. Run doctor --repair to demote them to pending until their dependencies integrate.`,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}}async function A9(e,t){let r=[],i=[];for(let n of await NC(e)){let a=Yo(n);if(t&&a.change!==t)continue;let o=Df.join(e.transactionsDir,n);try{let s=await Ju(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 $S(e,t){let r=Tt(e,"--repair"),i=Pe(e,"--strategy");if(i!==void 0&&i!=="continue"&&i!=="rollback")throw new I("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();$e(e);let a=await Q$(t),o=await x9(a,n);if(n&&o.length>0){let d=ZO(a,o[0]);if(!r){let m=await Ae(a,n)?await Ar({paths:a,name:n,details:!0}):void 0;return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...m?{result:m,continuation:m.continuation}:{},findings:[d]})}let f=await Ek(a,n);if(await Ae(a,n)){let h=await O(a,n);return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,workspaceFinishJournal:{quarantined:f,finding:d},state:h,continuation:await la(a,h)})}return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,workspaceFinishJournal:{quarantined:f,finding:d}})}let s=await A9(a,n);if(n&&s.findings.length>0){if(i)throw new I("--strategy is only available to the legacy transaction doctor");let f=await Ae(a,n)?await Ar({paths:a,name:n,details:!0}):void 0;if(r&&s.transactions.length===1&&s.findings.length===1){if(s.transactions[0].kind==="archive"){let m=await mf({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:await la(a,m.state)})}let h=await Bi({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await la(a,h)})}return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...f?{result:f,continuation:f.continuation}:{},findings:s.findings})}if(n&&await Ae(a,n)){if(i)throw new I("--strategy is only available to the legacy transaction doctor");let[d,f]=await Promise.all([QO(a,n),vk(a,n)]);if(d){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[d],continuation:y.continuation})}if(f&&!r){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[e0(a,n)],continuation:y.continuation})}let p=await O(a,n),h=await XO(a,n,p);if(h){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[h],continuation:y.continuation})}let m=await mn({paths:a,state:p}),v=C9(n,m);if(v&&(m.status==="incompatible"||!r)){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[v],continuation:y.continuation})}if(r){if(f){let C=await Bi({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:C.schema,stateVersion:C.state_version},state:C,continuation:await la(a,C)})}let y=await sv({paths:a,name:n});if(y.repaired)return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:y,continuation:await la(a,y.state)});let E=(await lt(G(a,n)).catch(()=>null))?.execution;if(E&&E.stage==="verifying"&&E.actor==="verifier"&&E.status==="running"&&E.verifierStartedAt===void 0){let C=Date.now()-Date.parse(E.startedAt);if(C>=S9){let x=await O(a,n),D=Xm({state:x,summary:`Verifier dispatch registered ${Math.round(C/6e4)} minutes ago and never confirmed startup; doctor repair recorded the failure`}),se=await en({file:gt(a,n),expectedStateVersion:x.state_version,next:D,containedRoot:a.nativeRoot});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:{verifierTakeover:!0,waitedMinutes:Math.round(C/6e4)},continuation:await la(a,se)})}}let N=await Rs({paths:a,name:n,recoverUnknownRuntimeCheck:!0});if(N.reason==="execution-active")return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:N,continuation:await la(a,N.state)});let P=await A(a,`repair Native Supervisor dependencies ${n}`,async()=>{let C=await J(a,n),x=C?.children.filter(D=>D.status==="ready"&&!Mc(D.dependsOn,C.children))??[];if(x.length===0||!C)return[];for(let D of x)D.status="pending",D.blocker=null;return await oe(a,C),x.map(({name:D})=>D)});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,...P.length>0?{supervisorDependencyRepair:P}:{},result:N,continuation:await la(a,N.state)})}let g=await YO(a,n,p);if(g){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[g],continuation:y.continuation})}let w=await UO(a,n);if(w){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[w],continuation:y.continuation})}let k=await J(a,n,{diagnostics:!0}),b=k&&k.children.filter(y=>y.status==="ready"&&!Mc(y.dependsOn,k.children));if(k&&b&&b.length>0){let y=await Ar({paths:a,name:n,details:!0});return kn({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:y,findings:[_9(n,k,b)],continuation:y.continuation})}let R=await Ar({paths:a,name:n,details:!0});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:R,continuation:R.continuation})}if(n){if(r){let d=await Bi({paths:a,name:n});return V("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:d.schema,stateVersion:d.state_version},state:d,continuation:await la(a,d)})}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 c=await KO(a),l=s;if(c.length>0||l.findings.length>0||o.length>0){if(i)throw new I("--strategy is only available to the legacy transaction doctor");if(r){let N=await Of({paths:a,repair:!0,projectOnly:!0}),P=[],C=[];for(let U of o)C.push({change:U.name,quarantined:await Ek(a,U.name)});for(let U of l.transactions)U.kind==="archive"?await mf({paths:a,name:U.change}):await Bi({paths:a,name:U.change}),P.push({kind:U.kind,change:U.change,transactionId:U.journal.id});let x=[];for(let U of c){let Le=await sv({paths:a,name:U});Le.repaired&&x.push({change:U,reason:Le.reason??"Native confirmed requirements changed"})}let D=await $S([],t),se=D.data&&typeof D.data=="object"&&!Array.isArray(D.data)?D.data:{};return{...D,data:{...se,repaired:!0,repairedPortableTransactions:P,repairedWorkspaceFinishJournals:C,repairedShapeConfirmations:x,repairFindings:N.findings}}}let d=await E9(a),f=new Set(c),p=new Set(l.transactions.filter(N=>N.kind==="migration").map(({change:N})=>N)),h=d.filter(N=>!f.has(N)),[m,v,g,w,k,b,R,y]=await Promise.all([Promise.all(c.map(N=>Ar({paths:a,name:N}))),Promise.all(c.map(N=>QO(a,N))),Promise.all(c.map(N=>vk(a,N))),Promise.all(c.map(async N=>{let P=await O(a,N);return YO(a,N,P)})),Promise.all(c.map(async N=>{let P=await O(a,N);return XO(a,N,P)})),Promise.all(c.map(N=>UO(a,N))),Promise.all(h.map(N=>Of({paths:a,name:N}))),Of({paths:a,projectOnly:!0})]),S=P9([...v.filter(N=>N!==null),...c.flatMap((N,P)=>g[P]&&!p.has(N)?[e0(a,N)]:[]),...w.filter(N=>N!==null),...k.filter(N=>N!==null),...b.filter(N=>N!==null),...l.findings,...o.map(N=>ZO(a,N)),...h.map(N=>({severity:"error",code:"portable-migration-required",message:`Native active change ${N} requires migration to portable Runtime`,path:Df.join(a.changesDir,N,"comet-state.yaml"),repair:"migrate"})),...R.flatMap(({findings:N})=>N),...y.findings]),E={healthy:S.every(N=>N.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:S};return E.healthy?V("doctor",E):kn(E)}let u=await Of({paths:a,...n?{name:n}:{},repair:r,...i?{recoveryStrategy:i}:{}});return u.healthy?V("doctor",u):{command:"doctor",exitCode:65,data:u,error:{code:"invalid-data",message:"Native project needs attention"}}}import{promises as G9}from"fs";import Ce from"path";import i0 from"node:path";async function r0(e=2e3){return process.stdin.isTTY?{text:""}:!Number.isFinite(e)||e<1?{text:null}:process.stdin.readableEnded?{text:""}:await new Promise(t=>{let r=!1,i=0,n=[],a=setTimeout(()=>o({text:null}),Math.ceil(e)),o=d=>{r||(r=!0,clearTimeout(a),process.stdin.removeListener("data",s),process.stdin.removeListener("end",c),process.stdin.removeListener("close",l),process.stdin.removeListener("error",u),process.stdin.pause(),t(d))},s=d=>{let f=Buffer.isBuffer(d)?d:Buffer.from(d),p=1048576-i;if(p<=0){o({text:null});return}let h=f.subarray(0,p);n.push(h),i+=h.length,f.length>h.length&&o({text:null})},c=()=>o({text:Buffer.concat(n,i).toString("utf8")}),l=()=>{process.stdin.readableEnded||o({text:null})},u=()=>o({text:null});process.stdin.on("data",s),process.stdin.once("end",c),process.stdin.once("close",l),process.stdin.once("error",u),a.unref(),process.stdin.resume()})}var I9=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),j9=new Set(["glob","grep","listfiles","read","readfile","search","view"]),n0=["file_path","filePath","path","target_file","targetFile"],a0=["file_paths","filePaths","paths","files","targets"],o0=["operations","edits"],T9=["patch","diff","patchText","patch_text","changes"];function HS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function OS(e){return e.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function $9(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 O9(e){for(let t of["cwd","working_directory","workspaceRoot"]){let r=e[t];if(!(typeof r!="string"||!r.trim()||!i0.isAbsolute(r.trim())))return i0.resolve(r.trim())}}function D9(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 H9(e){for(let t of["hook_event_name","hookEventName","event_name","eventName"]){let r=e[t];if(typeof r=="string"&&r.trim())return OS(r)}}function F9(e){for(let t of["task","prompt","user_prompt","userPrompt"]){let r=e[t];if(typeof r=="string"&&r.trim())return r.trim()}}function q9(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 L9(e){for(let t of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(e[t]!==void 0)return q9(e[t]);return e}function DS(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 Os(e,t){if(typeof t=="string"){let r=t.trim();r&&e.push(r);return}if(Array.isArray(t)){for(let r of t)Os(e,r);return}if(HS(t)){for(let r of n0)Os(e,t[r]);for(let r of a0)Os(e,t[r]);for(let r of o0)Os(e,t[r])}}function M9(e,t){let r=[],i=[t,e].filter(HS);for(let n of i){for(let a of n0)Os(r,n[a]);for(let a of a0)Os(r,n[a]);for(let a of o0)Os(r,n[a]);for(let a of T9){let o=n[a];typeof o=="string"&&r.push(...DS(o))}}return typeof t=="string"&&r.push(...DS(t)),[...new Set(r)]}function Hf(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(wf(e))}catch{let s=DS(e);return s.length>0?{intent:"write",targets:[...new Set(s)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!HS(r))return{intent:"unknown",targets:[],toolName:null};let i=$9(r),n=M9(r,L9(r)),a=O9(r),o=D9(r);if(H9(r)==="beforeagentstart"){let s=F9(r);return{intent:"context",targets:[],toolName:null,...s?{task:s}:{},...a?{cwd:a}:{},...o?{sessionId:o}:{}}}return i&&I9.has(OS(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i&&j9.has(OS(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}:{}}}async function s0(e={}){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Hf("",t);let r=await(e.readStdin??r0)();r.text===null&&(process.stderr.write(`[COMET-HOOK] stdin timeout: the host did not provide hook input within the expected window
|
|
357
|
+
`),process.exit(1));try{return Hf(r.text,t)}catch{return Hf("",t)}}ot();Z();var B9=new Set([".md",".markdown"]),V9=new Set([".md",".markdown",".rst",".txt"]),W9=new Set(["docs","doc","documentation",".github"]),z9=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function c0(e){return e.replaceAll("\\","/").replace(/^\.\//u,"")}function J9(e,t){for(let r of t){let i=c0(r).replace(/\/+$/u,"");if(i&&(e===i||e.startsWith(`${i}/`)))return!0}return!1}function l0(e,t=[]){let r=c0(e);if(!r||r.endsWith("/")||J9(r,t))return!1;let i=r.split("/"),n=i[i.length-1],a=n.lastIndexOf("."),o=a===-1?"":n.slice(a).toLowerCase();return i.length===1?B9.has(o)||z9.some(s=>s.test(n)):W9.has(i[0])&&V9.has(o)}Xs();var K9=new Set(["brief.md","children.yaml","comet-state.yaml","verification.md","capability-association.yaml"]),d0=new Set(["comet-state.yaml","verification.md","capability-association.yaml"]);function qS(e){let t=e.split("/");return t.length===3&&t[0]==="specs"&&t[1]!==void 0&&cn.test(t[1])&&(t[2]==="spec.md"||t[2]===Ys)}function ug(e,t){if(!Qt(e,t))return null;let r=Ce.relative(e,t).replaceAll("\\","/"),[i,...n]=r.split("/");if(!i||!cn.test(i))return null;if(n.length===0)return{name:i,relative:""};let a=n.join("/");return K9.has(a)?{name:i,relative:a}:qS(a)?{name:i,relative:a}:null}function U9(e,t){return Qt(e.runtimeDir,t)||Ce.relative(e.projectRoot,t).replaceAll("\\","/")===".comet/current-change.json"}function Y9(e,t,r){let i=Ce.join(e.projectRoot,".comet","comet");if(Qt(e.nativeRoot,t)||Ce.resolve(i)===Ce.resolve(e.nativeRoot))return null;let n=ug(Ce.join(i,"changes"),t);return n&&r.has(n.name)?n:null}function f0(e){return e==="brief.md"?"data.artifacts.briefPath":e==="children.yaml"?"data.artifacts.childrenPath":e.startsWith("specs/")?"data.artifacts.specsDir":"data.artifacts.changeDir"}function p0(e,t,r){return`Published Native specs are updated through Archive. Read ${Ce.join(e,"specs",Ce.relative(t,r))}, merge the original edit there, and retry the write against that exact target; do not overwrite existing content.`}function u0(e,t,r,i={}){if(!Qt(e,r))return null;if(U9(t,r)){let s=Ce.relative(t.projectRoot,r).replaceAll("\\","/"),c=s.match(/^\.comet\/runtime\/native\/changes\/([^/]+)(?:\/|$)/u)?.[1];return{allowed:!1,reason:`Native Runtime-owned path ${s}. Run ${c?`comet native status ${c} --json`:"comet native status --json"} in ${t.projectRoot}, follow its continuation, and retry; do not edit Runtime files directly.`,workflow:"native",...c?{change:c}:{}}}let n=Y9(t,r,i.registeredChanges??new Set);if(n){let s=Ce.join(t.changesDir,n.name,n.relative);return{allowed:!1,reason:`Native formal artifact target ${Ce.relative(e,r).replaceAll("\\","/")} is outside the configured artifact root. Use ${s} in ${t.projectRoot}; read existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:n.name}}let a=ug(t.changesDir,r);if(!a)return null;if(d0.has(a.relative))return{allowed:!1,reason:`Native Runtime-owned artifact ${Ce.relative(e,r).replaceAll("\\","/")}. Run comet native status ${a.name} --json in ${t.projectRoot} and follow its continuation; do not infer a mutation or edit the file directly.`,workflow:"native",change:a.name};if(i.allowCanonicalFormal===!1)return null;let o=Ce.join(t.changesDir,a.name,a.relative);return{allowed:!1,reason:`Native formal artifact target ${Ce.relative(e,r).replaceAll("\\","/")} is not registered. Run comet native new ${a.name} in ${t.projectRoot}. Use the response ${f0(a.relative)} to locate ${o}; read initialized or existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:a.name}}function FS(e){return e.length===0?null:e.length===1?e[0]:{...e[0],reason:e.map(t=>t.reason).join(`
|
|
358
|
+
`)}}function X9(e,t,r,i,n,a){let o=Ce.relative(e,n).replaceAll("\\","/"),s=Ce.join(t.changesDir,i.name,i.relative);return{allowed:!1,reason:a?`Native formal artifact target ${o} belongs to registered change ${i.name}, not selected change ${r}. Run comet native select ${i.name} in ${t.projectRoot}, then read ${s} and merge the original edit.`:`Native formal artifact target ${o} belongs to unregistered change ${i.name}, not selected change ${r}. Run comet native new ${i.name} --isolation worktree in ${t.projectRoot}. Use the response ${f0(i.relative)} to locate ${s}; read initialized or existing content and merge the original edit.`,workflow:"native",change:r}}function h0(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 Q9(e){let{projectRoot:t,paths:r,state:i,request:n}=e,a=X(r,i.name),o=[],s=[],c=[],l=[],u=[],d=await m0(t),f=!1,p=!1,h=!1;for(let m of n.targets){let v=Ce.resolve(t,m);if(!Qt(t,v)){h=!0;continue}let g=Ce.relative(t,v).replaceAll("\\","/");if(g===".comet/config.yaml"){p=!0;continue}if(!Qt(r.nativeRoot,v)){if(await om(t,v,[Ce.join(t,".comet"),r.nativeRoot])){f=!0;continue}if(!d&&v0(r,g)){l.push(g);continue}c.push(g);continue}if(!Qt(a,v)){u.push({allowed:!1,reason:Qt(r.specsDir,v)?p0(a,r.specsDir,v):"Portable Native control state is Runtime-owned",workflow:"native",phase:i.phase,change:i.name});continue}let w=Ce.relative(a,v).replaceAll("\\","/");if(w==="brief.md"||w==="children.yaml"||w.startsWith("specs/")&&Z9(w)){o.push(w);continue}if(w.startsWith("specs/")){s.push(w);continue}u.push({allowed:!1,reason:`${w||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:i.phase,change:i.name})}return s.length>0&&u.push({allowed:!1,reason:s.map(g0).join(`
|
|
359
|
+
`),workflow:"native",phase:i.phase,change:i.name}),u.length>0?FS(u):o.length>0&&(c.length>0||l.length>0)?{allowed:!1,reason:"Formal Native requirements must be edited in separate actions from implementation or documentation files",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 Ns({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}:c.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 ea({paths:r,name:i.name,reason:`Observed implementation write before ${c.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:h0(i),workflow:"native",phase:i.phase,change:i.name}:l.length>0?{allowed:!0,reason:"Native neutral document write: documentation edits stay outside the implementation scope and do not return the change to Build",workflow:"native",phase:i.phase,change:i.name}:f?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:p?"Native control artifact write":h?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function Qt(e,t){let r=Ce.relative(e,t);return r===""||!r.startsWith("..")&&!Ce.isAbsolute(r)}async function m0(e){return(await te(e))?.native?.document_writes==="revert"}function v0(e,t){return l0(t,[Ce.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),".comet"])}function g0(e){let t=e.split("/"),r=t[0]==="specs"&&t[1]&&cn.test(t[1])?t[1]:null;return`Native formal Spec artifacts must use ${r?`specs/${r}/spec.md (or specs/${r}/${Ys} for delta metadata)`:`specs/<capability>/spec.md (or specs/<capability>/${Ys} for delta metadata)`}; received ${e}`}function Z9(e){return qS(e)}function e3(e,t,r){return r.targets.length>0&&r.targets.every(i=>{let n=Ce.resolve(e,i);return Qt(e,n)?Ce.relative(e,n).replaceAll("\\","/")===".comet/config.yaml"||Qt(t,n):!0})}async function t3(e){let t=await te(e);if(!t||!(t.workflows??[t.default_workflow]).includes("native"))return null;let r=await Se(e,t.native.artifact_root),i;try{i=await G9.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 Ae(r,a.name)){let o=await O(r,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await Me(r,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:r,changes:n}}async function r3(e,t){let r=await te(e);if(!r||!(r.workflows??[r.default_workflow]).includes("native"))return null;let i=await Se(e,r.native.artifact_root);try{if(await Ae(i,t)){let a=await O(i,t);return{paths:i,changes:a.archived?[]:[{kind:"portable",state:a}]}}let n=await Me(i,t);return{paths:i,changes:n.archived?[]:[{kind:"legacy",state:n}]}}catch(n){if(n.code==="ENOENT")return{paths:i,changes:[]};throw n}}var i3=am("nativeActiveContext",e=>t3(e));async function n3(e,t){let r=await te(e);if(!r||!(r.workflows??[r.default_workflow]).includes("native"))return null;let i=await Se(e,r.native.artifact_root);try{let n=await Ae(i,t)?await O(i,t):await Me(i,t);return n.archived?null:{workflow:"native",name:n.name,phase:n.phase}}catch(n){if(n.code==="ENOENT")return null;throw n}}async function w0(){let{intent:e,targets:t}=await s0();return{intent:e,targets:t}}async function y0(e,t,r){let i=r?await r3(e,r):await i3(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){let m=[];for(let g of t.targets){let w=u0(e,i.paths,Ce.resolve(e,g));w&&m.push(w)}let v=FS(m);return v||{allowed:!0,reason:e3(e,i.paths.nativeRoot,t)?"Native control artifact write":"No Native changes exist"}}let n;if(r){if(n=i.changes.find(m=>m.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 m=await Tj(i.paths);if(n=i.changes.find(v=>v.state.name===m),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state,o=new Set(i.changes.map(({state:m})=>m.name)),s=new Map,c=[];for(let m of t.targets){let v=Ce.resolve(e,m),g=u0(e,i.paths,v,{allowCanonicalFormal:!1,registeredChanges:o});if(g){c.push(g);continue}let w=ug(i.paths.changesDir,v);if(w&&w.name!==a.name){let R=o.has(w.name);if(!R&&r){let y=s.get(w.name);y||(y=n3(e,w.name).then(Boolean),s.set(w.name,y)),R=await y}c.push(X9(e,i.paths,a.name,w,v,R));continue}if(!Qt(e,v))continue;if(Qt(i.paths.specsDir,v)){let R=n.kind==="portable"?X(i.paths,a.name):pe(i.paths,a.name);c.push({allowed:!1,reason:p0(R,i.paths.specsDir,v),workflow:"native",phase:a.phase,change:a.name});continue}if(!Qt(i.paths.nativeRoot,v))continue;let k=n.kind==="portable"?X(i.paths,a.name):pe(i.paths,a.name);if(Qt(k,v)){let R=Ce.relative(k,v).replaceAll("\\","/");if(R==="brief.md"||R==="children.yaml"||qS(R))continue;c.push({allowed:!1,reason:R.startsWith("specs/")?g0(R):`${R||"change directory"} is Runtime-owned. Run comet native status ${a.name} --json in ${i.paths.projectRoot} and follow its continuation; do not edit it directly.`,workflow:"native",phase:a.phase,change:a.name});continue}let b=Ce.relative(e,v).replaceAll("\\","/");c.push({allowed:!1,reason:`Native-managed path ${b} is not an editable artifact for ${a.name}. Run comet native status ${a.name} --json in ${i.paths.projectRoot} and follow its continuation.`,workflow:"native",phase:a.phase,change:a.name})}let l=FS(c);if(l)return l;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 Q9({projectRoot:e,paths:i.paths,state:n.state,request:t});let u=!1,d=!1,f=!1,p=!1,h=await m0(e);for(let m of t.targets){let v=Ce.resolve(e,m);if(!Qt(e,v)){d=!0;continue}let g=Ce.relative(e,v).replaceAll("\\","/");if(g===".comet/config.yaml"){u=!0;continue}if(Qt(i.paths.nativeRoot,v)){let w=ug(i.paths.changesDir,v);if(w?.name===a.name){if(d0.has(w.relative))return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${g}`,workflow:"native",phase:a.phase,change:a.name};u=!0;continue}return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${g}`,workflow:"native",phase:a.phase,change:a.name}}if(await om(e,v,[Ce.join(e,".comet"),i.paths.nativeRoot])){f=!0;continue}if(!h&&v0(i.paths,g)){p=!0;continue}return{allowed:!1,reason:h0(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:u?"Native control artifact write":d?"Write target is outside the guarded project":f?"Native configured Hook allow path":p?"Native neutral document write: documentation edits stay outside the implementation scope":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}async function N0(e,t){let r=Pe(e,"--hook-output");if(r!==void 0&&r!=="copilot")throw new I("--hook-output must be copilot");$e(e);let i=await y0(t,await w0());return r==="copilot"?{command:"hook-guard",exitCode:0,data:i,text:i.allowed?`{}
|
|
360
360
|
`:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:i.reason})}
|
|
361
361
|
`}:i.allowed?{command:"hook-guard",exitCode:0,data:i}:{command:"hook-guard",exitCode:2,data:i,error:{code:"blocked",message:i.reason}}}ot();Z();async function b0(e,t){let r=Pe(e,"--root"),i=await te(t),n=Jv(e,i?.native.language??"en");if($e(e),i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let a=Aa(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:jx(i.native.snapshot.exclude)}}}:Mo(a,n),s=await Se(t,o.native.artifact_root);return await wh(s),await Qu(t),await Dr(t,o),V("init",{projectRoot:t,artifactRoot:o.native.artifact_root,nativeRoot:s.nativeRoot,language:n},`Initialized Comet Native at ${s.nativeRoot}
|
|
362
|
-
`)}ot();Oe();import{promises as Q3}from"node:fs";import fg from"node:path";Ht();Xs();_n();Fo();import{createHash as F0}from"node:crypto";import{promises as Ol}from"node:fs";import Dt from"node:path";fr();import{createHash as n3}from"node:crypto";import{AsyncLocalStorage as a3}from"node:async_hooks";var o3=new a3;function s3(e,t){let r=Ed(e),i=t.runGit??_,n=o3.getStore(),a=n?.active?n.observations:void 0,o=a?.get(r)?.get(i);if(o)return o;let s=r;try{let l=i(r,["remote","get-url","origin"]).trim();if(l)s=l;else throw new Error("No origin")}catch{try{let l=i(r,["rev-parse","--git-common-dir"]).trim();l&&(s=Ed(r,l))}catch{}}let c={identity:S0(s),name:u3(s)};if(a){let l=a.get(r)??new Map;l.set(i,c),a.set(r,l)}return c}function c3(e,t={}){return s3(e,t).identity}function l3(e){let t=S0(e),i=(t.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",n=n3("sha256").update(t,"utf8").digest("hex").slice(0,8);return`${i.slice(0,40)}-${n}`}function k0(e,t={}){return l3(c3(e,t))}function u3(e){return(e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-zA-Z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project"}function S0(e){let t=e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return t||"project"}var ua=class extends Error{code;constructor(t,r,i){super(r,i),this.name="BoundedHttpRequestError",this.code=t}};async function d3(e,t){if(!e.body){let s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>t)throw new ua("response-too-large","HTTP response exceeds byte limit");return s}let r=e.body.getReader(),i=[],n=0;try{for(;;){let s=await r.read();if(s.done)break;if(n+=s.value.byteLength,n>t)throw await r.cancel(),new ua("response-too-large","HTTP response exceeds byte limit");i.push(s.value)}}finally{r.releaseLock()}let a=new Uint8Array(n),o=0;for(let s of i)a.set(s,o),o+=s.byteLength;return a}async function E0(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs);try{let i=await(e.fetch??globalThis.fetch)(e.url,{...e.init,signal:t.signal}),n=i.ok?await d3(i,e.maxResponseBytes):new Uint8Array;return{response:i,bytes:n}}catch(i){throw i instanceof ua?i:t.signal.aborted?new ua("timeout","HTTP request timed out",{cause:i}):new ua("request-failed","HTTP request failed",{cause:i})}finally{clearTimeout(r)}}import R0 from"node:path";var f3=/^[a-z0-9][a-z0-9._-]{1,127}$/u,_0=2e3,p3=1024,h3=32,m3=32,v3=32,g3=16,w3=16,A0=32,y3=128,N3=32,b3=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),k3=new Set(["trial","proven","enforced","superseded"]),S3=new Set(["automatic","user","repository"]),E3=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function $l(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Zr(e,t,r=_0){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e.trim()}function LS(e,t){let r=Zr(e,t,128);if(!f3.test(r))throw new Error(`${t} must use a stable record id`);return r}function Tl(e,t,r,i){if(e===void 0)return[];if(!Array.isArray(e)||e.length>r)throw new Error(`${t} must be a bounded list`);return e.map((n,a)=>i(n,a))}function I0(e,t,r,i){if(!Array.isArray(e)||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty bounded list`);return e.map((n,a)=>i(n,a))}function BS(e,t){let r=Zr(e,t,p3).replaceAll("\\","/");if(R0.posix.isAbsolute(r)||R0.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(i=>i===".."))throw new Error(`${t} must be a project-relative path`);return r}function R3(e,t,r=h3){return Tl(e,t,r,(i,n)=>BS(i,`${t}[${n}]`))}function P0(e,t,r=m3){return Tl(e,t,r,(i,n)=>Zr(i,`${t}[${n}]`,512))}function MS(e,t,r=_0){if(e!==void 0)return Zr(e,t,r)}function x0(e,t){if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer`);return Number(e)}function Ff(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer`);return Number(e)}function j0(e,t){let r=$l(e,t),i=r.lineStart,n=r.lineEnd,a=i===void 0?void 0:x0(i,`${t}.lineStart`),o=n===void 0?void 0:x0(n,`${t}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${t}.lineEnd must be greater than or equal to lineStart`);let s=MS(r.anchor,`${t}.anchor`,256),c=MS(r.evidence,`${t}.evidence`,1024);return{source:BS(r.source,`${t}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function P3(e,t){let r=$l(e,`conclusions[${t}]`);return{text:Zr(r.text,`conclusions[${t}].text`),sources:I0(r.sources,`conclusions[${t}].sources`,A0,(i,n)=>j0(i,`conclusions[${t}].sources[${n}]`))}}function x3(e,t){let r=$l(e,`relations[${t}]`),i=Zr(r.type,`relations[${t}].type`,64);if(!E3.has(i))throw new Error(`relations[${t}].type is unsupported`);return{type:i,targetId:LS(r.targetId,`relations[${t}].targetId`),sources:I0(r.sources,`relations[${t}].sources`,A0,(n,a)=>j0(n,`relations[${t}].sources[${a}]`))}}function C3(e,t){let r=$l(e,`verification[${t}]`),i=MS(r.expected,`verification[${t}].expected`);return{command:Zr(r.command,`verification[${t}].command`),...i===void 0?{}:{expected:i}}}function _3(e,t){let r=$l(e,`sourceVersions[${t}]`),i=r.digest;if(i!==void 0&&(typeof i!="string"||!/^[a-f0-9]{64}$/u.test(i)))throw new Error(`sourceVersions[${t}].digest must be a SHA-256 hash`);return{source:BS(r.source,`sourceVersions[${t}].source`),size:Ff(r.size,`sourceVersions[${t}].size`),modifiedAt:Ff(r.modifiedAt,`sourceVersions[${t}].modifiedAt`),...i===void 0?{}:{digest:i}}}function A3(e,t){return e.reduce((r,i)=>r+i.sources.length,0)+t.reduce((r,i)=>r+i.sources.length,0)}function C0(e){let t=Zr(e,"updatedAt",64);if(Number.isNaN(Date.parse(t)))throw new Error("updatedAt must be an ISO-8601 timestamp");return t}function I3(e){let t=$l(e,"record"),r=Zr(t.type,"type",64);if(!b3.has(r))throw new Error("type is unsupported");let i=Zr(t.state,"state",32);if(!k3.has(i))throw new Error("state is unsupported");let n=Zr(t.authority,"authority",32);if(!S3.has(n))throw new Error("authority is unsupported");let a=Tl(t.conclusions,"conclusions",v3,P3),o=Tl(t.relations,"relations",g3,x3);if(A3(a,o)>y3)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Tl(t.sourceVersions,"sourceVersions",N3,_3);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:LS(t.id,"id"),projectId:LS(t.projectId,"projectId"),type:r,state:i,authority:n,title:Zr(t.title,"title"),summary:Zr(t.summary,"summary"),applicablePaths:R3(t.applicablePaths,"applicablePaths"),operations:P0(t.operations,"operations"),phases:P0(t.phases,"phases"),conclusions:a,relations:o,verification:Tl(t.verification,"verification",w3,C3),sourceVersions:s,applicationCount:Ff(t.applicationCount,"applicationCount"),successCount:Ff(t.successCount,"successCount"),failureCount:Ff(t.failureCount,"failureCount"),...t.lastAppliedAt===void 0?{}:{lastAppliedAt:C0(t.lastAppliedAt)},updatedAt:C0(t.updatedAt)}}function Eo(e){return I3(e)}var j3=1024*1024,T3=512,D0=200,H0=1600,$3=5e3,O3=8,D3=512*1024,H3=32;function xe(e,t,r=!1){if(typeof e!="string")return null;let i=[...e].map(n=>{let a=n.codePointAt(0)??0;return a<32||a===127?" ":n}).join("").trim().slice(0,t);return r&&!i?null:i}function WS(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;let r=xe(t.code,64,!0),i=xe(t.message,240,!0);return r&&i?{code:r,message:i}:null}).filter(t=>t!==null).slice(0,O3):[]}function qf(){return[]}function T0(e){let t={...e};return delete t.evidence,t}function $0(e){return{...e,conclusions:e.conclusions.map(t=>({...t,sources:t.sources.map(T0)})),relations:e.relations.map(t=>({...t,sources:t.sources.map(T0)}))}}function F3(e){if(e.kind==="upsert")return{kind:"upsert",record:$0(e.record)};if(e.kind!=="experience-delta")return e;let t=e.delta,r=t.payload;r?.kind==="record"?r={kind:"record",record:$0(Eo(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:xe(r.projectId,128)??"",commands:Lf(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:i,...n}=t,a={...n,statement:xe(t.statement,4e3)??"",...t.title===void 0?{}:{title:xe(t.title,512)??""},applicability:{...t.applicability.projectId===void 0?{}:{projectId:xe(t.applicability.projectId,128)??""},...t.applicability.paths===void 0?{}:{paths:Lf(t.applicability.paths,32,512)},...t.applicability.operations===void 0?{}:{operations:Lf(t.applicability.operations,16,128)},...t.applicability.phases===void 0?{}:{phases:Lf(t.applicability.phases,16,128)},...t.applicability.tasks===void 0?{}:{tasks:Lf(t.applicability.tasks,16,512)}},evidence:t.evidence.slice(0,H3).map(o=>({...o,summary:xe(o.summary,1e3)??"",...o.source===void 0?{}:{source:xe(o.source,512)??""},...o.anchor===void 0?{}:{anchor:xe(o.anchor,256)??""},...o.command===void 0?{}:{command:xe(o.command,2e3)??""}})),...r===void 0?{}:{payload:r}};return{...e,idempotencyKey:xe(e.idempotencyKey,256,!0)??"invalid",delta:a}}function Lf(e,t,r){return Array.isArray(e)?e.map(i=>xe(i,r)).filter(i=>!!i).slice(0,t):[]}function q3(e){if(e.kind==="search"){let t=e.query;return{kind:"search",task:xe(t.task,2e3)??"",...t.path?{path:xe(t.path,512)}:{},...t.phase?{phase:xe(t.phase,128)}:{},...t.operation?{operation:xe(t.operation,128)}:{},terms:t.terms.slice(0,28).map(r=>xe(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,e.limit??8))}}return e.kind==="list"?{kind:"list",...e.projectId?{projectId:xe(e.projectId,128)}:{},...e.type?{type:e.type}:{},...e.state?{state:e.state}:{},...e.authority?{authority:e.authority}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="manifest"?{kind:"manifest",...e.projectId?{projectId:xe(e.projectId,128)}:{},...e.state?{state:e.state}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="expand"?{kind:"expand",id:xe(e.id,128)??"",...e.projectId?{projectId:xe(e.projectId,128)}:{}}:{kind:"get",id:xe(e.id,128)??"",...e.projectId?{projectId:xe(e.projectId,128)}:{}}}function VS(e,t,r){if(!Array.isArray(e))return[];let i=[];for(let n of e.slice(0,500))try{let a=Eo(n);if(a.projectId!==r)throw new Error("Project mismatch");i.push(a)}catch{t()}return i}function L3(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return t(),null;let i=xe(e.content,H0,!0),n=xe(e.source,T3,!0);if(!i||!n)return t(),null;let a=e.title,o=a===void 0?void 0:xe(a,D0);if(a!==void 0&&o===null)return t(),null;let s=e.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return t(),null;let c,l=e.record;if(l!==void 0)try{if(c=Eo(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return t(),null}return{content:i,source:n,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function M3(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)&&"status"in e?e.status:e;if(!r||typeof r!="object"||Array.isArray(r))return t(),null;let i=r.provider,n=r.healthy,a=r.writable;if(i!=="remote"||typeof n!="boolean"||typeof a!="boolean")return t(),null;let o=r.recordCount,s=r.updatedAt;return{provider:"remote",healthy:n,writable:a,...Number.isSafeInteger(o)&&Number(o)>=0?{recordCount:Number(o)}:{},...typeof s=="string"?{updatedAt:s.slice(0,64)}:{},diagnostics:WS(r.diagnostics)}}function B3(e,t,r,i){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.kind??t.kind,o=WS(n.diagnostics);if(a==="list")return{kind:"list",records:VS(n.records,r,i),truncated:n.truncated===!0,diagnostics:o};if(a==="get"){let f=n.record,p=null;if(f!=null)try{if(p=Eo(f),p.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:p,diagnostics:o}}if(a==="expand"){let f=n.record,p=null;if(f!=null)try{if(p=Eo(f),p.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:p,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(n.items)?n.items.slice(0,500).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];let h=p,m=xe(h.id,128,!0),v=xe(h.title,D0,!0),g=xe(h.summary,H0,!0),w=h.type,k=h.memoryType,b=h.state,R=h.authority;if(!m||!v||!g||!["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"].includes(String(w))||k!=="project-model"&&k!=="project-policy"||!["trial","proven","enforced","superseded"].includes(String(b))||!["automatic","user","repository"].includes(String(R)))return r(),[];let y=E=>Array.isArray(E)?E.map(N=>xe(N,1024)).filter(N=>N!==null):[],S=Array.isArray(h.verification)?h.verification.slice(0,16).flatMap(E=>{if(!E||typeof E!="object"||Array.isArray(E))return r(),[];let N=xe(E.command,4e3,!0),P=xe(E.expected,2e3);return N?[{command:N,...P===null?{}:{expected:P}}]:[]}):[];return[{id:m,memoryType:k,type:w,state:b,authority:R,title:v,summary:g,applicablePaths:y(h.applicablePaths),operations:y(h.operations),phases:y(h.phases),sourceTypes:y(h.sourceTypes),verification:S}]}):[],truncated:n.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let f of Array.isArray(n.results)?(n.results??[]).slice(0,16):[]){let p=L3(f,r,i);if(!(!p||l.has(`${p.source}\0${p.title??""}`))){if(c+p.content.length>$3)break;l.add(`${p.source}\0${p.title??""}`),c+=p.content.length,s.push(p)}}let u=VS(n.records,r,i);return{kind:"search",hits:Array.isArray(n.hits)?(n.hits??[]).slice(0,40).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];try{let p=Eo(f.record);if(p.projectId!==i)throw new Error("Project mismatch");let h=f.score;return h!==void 0&&(typeof h!="number"||!Number.isFinite(h))?(r(),[]):[{record:p,...h===void 0?{}:{score:h}}]}catch{return r(),[]}}):u.map(f=>({record:f})),results:s,records:u,truncated:n.truncated===!0,diagnostics:o}}function V3(e,t,r,i){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.record,o;if(a===null)o=null;else if(a!==void 0)try{if(o=Eo(a),o.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:t.kind,changed:n.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(n.records)?{records:VS(n.records,r,i)}:{},diagnostics:WS(n.diagnostics)}}var dg=class{options;projectId;constructor(t){this.options=t,this.projectId=t.projectId??(t.projectRoot?k0(t.projectRoot):"project")}async status(){let t=this.options.config.token_env;if(t&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${t}。`};return this.report(a.code,a.message),{provider:"remote",healthy:!1,writable:!1,diagnostics:[a]}}let r=await this.request("status",{});if(r===null)return{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let i={value:!1},n=M3(r,()=>{i.value=!0});return!n||i.value?(this.report("remote-schema","Remote Project Knowledge status 响应格式无效。"),{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge status 响应格式无效。"}]}):n}async query(t){let r=t.kind==="search"?this.projectId:t.projectId??this.projectId,i=await this.request("query",q3(t),t.kind==="search"?void 0:t.projectId);if(i===null)return O0(t);let n={value:!1},a=B3(i,t,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),O0(t)):a}async apply(t){let r=(t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId)??this.projectId,i=await this.request("apply",F3(t),t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId);if(i===null)return{kind:t.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},a=V3(i,t,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:t.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(t,r,i=this.projectId){let n=this.options.config.token_env,a=this.token();if(n&&!a)return this.report("remote-token",`Remote Project Knowledge 未配置环境变量 ${n}。`),null;let o={schema:"comet.project-knowledge.provider.v1",operation:t,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:xe(i,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>D3)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await E0({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:j3,fetch:this.options.fetch,init:{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:s}});if(!c.ok)return this.report("remote-status",`Remote Project Knowledge 返回 HTTP ${c.status}。`),null;try{let u=JSON.parse(new TextDecoder().decode(l));return W3(u,t,o.projectId)?u.result:(this.report("remote-schema","Remote Project Knowledge 响应 envelope 无效。"),null)}catch{return this.report("remote-json","Remote Project Knowledge 返回了无效 JSON。"),null}}catch(c){return this.report("remote-failed",c instanceof ua&&c.code==="timeout"?"Remote Project Knowledge 请求超时。":"Remote Project Knowledge 请求失败。"),null}}report(t,r){this.options.reportDiagnostic?.({code:t,message:r})}token(){let t=this.options.config.token_env;return t?this.options.env?.[t]??process.env[t]:void 0}};function W3(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;let i=e;return i.schema==="comet.project-knowledge.provider.v1"&&i.operation===t&&i.projectId===r&&Object.prototype.hasOwnProperty.call(i,"result")}function O0(e){return e.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:qf()}:e.kind==="get"?{kind:"get",record:null,diagnostics:qf()}:e.kind==="expand"?{kind:"expand",record:null,diagnostics:qf()}:e.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:qf()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:qf()}}var q0=512,zS=256*1024,M0=8*1024*1024,z3=2e3,B0=Dt.join(".comet","runtime","native","capability-discovery-cache.json"),Mf="comet.native.capability-cache.v1",V0=512*1024,W0=32;function JS(e,t){let r=Dt.relative(Dt.resolve(e),Dt.resolve(t));return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}function J3(e,t){return Dt.relative(e,t).replaceAll(Dt.sep,"/")}function G3(e,t,r){e?.({code:t,message:r})}async function K3(e,t){if(!JS(t,e))return!1;try{let r=await Ol.lstat(e);return!r.isDirectory()||r.isSymbolicLink()?!1:JS(await Ol.realpath(t),await Ol.realpath(e))}catch{return!1}}async function KS(e){let t=Dt.resolve(e.projectRoot),r=Date.now()+z3,i=[],n=!0,a=0,o=async(c,l)=>{if(Date.now()>r){n=!1;return}if(!await K3(c,t))return;let u=async d=>{if(Date.now()>r||i.length>=q0){n=!1;return}let f;try{f=await Ol.readdir(d,{withFileTypes:!0})}catch{n=!1;return}for(let p of f.sort((h,m)=>h.name.localeCompare(m.name,"en"))){if(Date.now()>r){n=!1;return}if(p.isSymbolicLink())continue;let h=Dt.join(d,p.name);if(p.isDirectory()){await u(h);continue}if(!p.isFile()||!p.name.toLowerCase().endsWith(".md")||!JS(t,h))continue;let m=await Ol.stat(h);if(m.size>zS)continue;if(a+m.size>M0){n=!1;return}if(Date.now()>r){n=!1;return}let v=J3(t,h),g;try{g=await Wt(t,v,zS,{label:`${l} capability Spec`})}catch{n=!1;continue}if(a+=g.bytes.length,i.push({absolutePath:h,source:v,kind:l,size:m.size,mtimeMs:m.mtimeMs,contentHash:F0("sha256").update(g.bytes).digest("hex")}),i.length>=q0){n=!1;return}}};await u(c)};await o(Dt.resolve(t,...e.scope.currentSpecRoot.split("/")),"native-spec"),await o(Dt.resolve(t,...e.scope.archiveRoot.split("/")),"native-archive"),i.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=F0("sha256").update(JSON.stringify(i.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})))).digest("hex");return n||G3(e.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:i,fingerprint:s,complete:n}}function L0(e){return/^(?:#)\s+(.+)$/mu.exec(e)?.[1]?.trim()}function U3(e,t,r){let i=`${t}
|
|
363
|
-
${e}`.toLocaleLowerCase();return r.reduce((n,a)=>n+(i.includes(a.toLocaleLowerCase())?1:0),0)}var GS=class{constructor(t,r,i){this.projectRoot=t;this.manifest=r;this.reportDiagnostic=i}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(t){if(t.kind!=="search")throw new Error("Native capability discovery only supports search queries");let r=[],i=[],n=0;for(let a of this.manifest.sources){if(n+a.size>M0){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await Wt(this.projectRoot,a.source,zS,{label:`${a.kind} capability Spec`});n+=o.bytes.length;let s=o.bytes.toString("utf8"),c=
|
|
364
|
-
`)}}Pm();ls();fr();import{randomUUID as iD}from"node:crypto";import{promises as X0}from"node:fs";import Bf from"node:path";Vc();Pb();gd();Fe();as();function Fl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function me(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 Dl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>me(r,`${t}[${i}]`))}function t8(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Fl(t,`Native Builder check ${r}`);if(qe(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${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:me(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function pg(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Fl(t,`Native Runtime check ${r}`);if(qe(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${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:me(i.id,`Native Runtime check ${r} id`),name:me(i.name,`Native Runtime check ${r} name`),executable:me(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:me(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Q0(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:me(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function r8(e){let t=Fl(e,"Native Supervisor evidence");return qe(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:me(t.summary,"Native Supervisor evidence summary"),checks:Dl(t.checks,"Native Supervisor evidence checks"),acceptance:_m(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:me(t.receiptRef,"Native Supervisor receipt ref")}}}function i8(e){let t=Fl(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),qe(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=Fl(t.review,"Native Builder review");if(qe(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:me(n.summary,"Native Builder review summary"),reviewer_execution_ref:me(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:me(t.summary,"Native Builder summary"),addressed_acceptance_ids:Dl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:t8(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:pg(t.verification_checks)}:{},known_limits:Dl(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return qe(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:pg(t.checks)};if(t.kind==="retry-checks")return qe(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:Dl(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return qe(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:me(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:me(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:vd(t.response,"/response")};if(t.kind==="verifier-started")return qe(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:me(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:me(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return qe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:me(t.summary,"Native Verifier execution error summary"),...Q0(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return qe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:me(t.summary,"Native unavailable Verifier summary"),...Q0(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return qe(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),candidateCommit:me(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return qe(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),reason:me(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(qe(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:me(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return qe(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return qe(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),reason:me(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(qe(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:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:r8(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(qe(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),checks:pg(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Dl(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=Fl(i,"Native Supervisor material");return qe(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:me(a.name,"Native Supervisor material name"),content:me(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return qe(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:me(t.child,"Native Supervisor child"),checks:pg(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Dl(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function QS(e,t){let r=Bf.resolve(t,e),i=await X0.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(wf(await X0.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return i8(n)}function n8(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function a8(e){return e.kind.startsWith("supervisor-")}function o8(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function Z0(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function US(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function s8(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function YS(e){let t=await lt(G(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function ZS(e){let t=await mn({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await J(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await nt({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(a8(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&n8(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(s8(e.state,e.input.addressed_acceptance_ids),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&&Wr(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(Z0(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");Wr(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(Z0(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await lt(G(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(d=>d.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){US(e.state);let c=await YS({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");Wr(o,o8(e.input));return}if(e.input.kind==="verifier-started"){US(e.state);let c=await YS({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){US(e.state);let c=await YS({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<Mn)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Wr(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Wr(r.integration.worktree,c.checks)}}function eD(e){return`${Et}:${e}:${iD()}`}function tD(e,t,r,i){if(Bf.resolve(_(e.projectRoot,["rev-parse","--show-toplevel"]))!==Bf.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(_(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!zr(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(_(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{_(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 c8(e,t){let r=ie(e.projectRoot),i=Bf.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Bf.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=_(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!zr(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{_(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 Hl(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Et)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function l8(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function rD(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Hl(r),s=l8(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Et,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:X(t,r.name),supervisorStateRef:a?ss(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,scopeCount:c.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,runtimeChecks:i.map(l=>({...l})),builderReportedChecks:o.checks.map(l=>({...l})),builderKnownLimits:o.known_limits.map(l=>({...l})),startupInstruction:'As this Verifier, submit the startup receipt first: save {"kind":"verifier-started","candidateId":"<candidateId above>","verifierExecutionRef":"<verifierExecutionRef above>"} as a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It only records that this Verifier actually started; a repeat submission is accepted without side effects. Then read the scenarios and proceed.',evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function XS(e){Hl(e.state);let t=await lt(G(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 nD(e){let t=e.input,r=await O(e.paths,e.name),i=await mn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await J(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:h})=>h==="integrated"||h==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:h})=>h==="integrated"||h==="archived");if(n&&t.kind==="supervisor-checks"){let h=await Rb({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await J(e.paths,e.name),v=m?.children.find(({name:g})=>g===t.child)?.task;return{state:r,supervisorState:m,supervisorTask:v&&v.runId===t.runId?Ua(v,e.name,e.paths.projectRoot):null,checks:[],checkExecution:h,requestChecks:null,verifierDispatch:null,continuation:L(r)}}if(n&&t.kind==="supervisor-builder-result")return A(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:b})=>b===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{tD(m.task,t.candidateCommit,"builder",`comet/supervisor/${h.parent}/${t.child}`)}catch(b){throw await oe(e.paths,kd(h,{child:t.child,runId:t.runId,reason:b.message})),b}let v=m.task.projectRoot,g=UN(h,t),w=bd(g,{role:"verifier",child:t.child,projectRoot:v,runId:iD()});await oe(e.paths,w.state);let k=await O(e.paths,e.name);return{state:k,supervisorTask:Ua(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:L(k)}});if(n&&t.kind==="supervisor-builder-failure")return A(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let v=Am(h,{child:t.child,runId:t.runId,reason:t.reason});await oe(e.paths,v);let g=await O(e.paths,e.name);return{state:g,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(g)}});if(n&&t.kind==="supervisor-retry-builder")return A(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=XN(h,{child:t.child,expectedStateVersion:t.stateVersion});await oe(e.paths,m);let v=await O(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(v)}});if(n&&t.kind==="supervisor-reconnect")return A(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child)?.task;if(!m||m.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{c8(m,`comet/supervisor/${h.parent}/${t.child}`)}catch(w){throw await oe(e.paths,kd(h,{child:t.child,runId:t.runId,reason:w.message})),w}let v=KN(h,{child:t.child,runId:t.runId});await oe(e.paths,v.state);let g=await O(e.paths,e.name);return{state:g,supervisorState:v.state,supervisorTask:Ua(v.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:L(g)}});if(n&&t.kind==="supervisor-cancel")return A(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=Am(h,{child:t.child,runId:t.runId,reason:t.reason});await oe(e.paths,m);let v=await O(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(v)}});if(n&&t.kind==="supervisor-verifier-result")return A(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:k})=>k===t.child);if(!m?.task||m.task.role!=="verifier"||!m.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{tD(m.task,m.candidateCommit,"verifier",`comet/supervisor/${h.parent}/${t.child}`)}catch(k){throw await oe(e.paths,kd(h,{child:t.child,runId:t.runId,reason:k.message})),k}let v=t.evidence.receiptRef||t.verdict==="pass"?await il({paths:e.paths,parent:e.name,task:m.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!v||v.checks.some(({status:k,exitCode:b})=>k!=="passed"||b!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=YN(h,{...t,evidence:{...t.evidence,checks:v?.checks.map(({name:k,status:b})=>`${k}: ${b}`)??[],execution:structuredClone(m.task)}});await oe(e.paths,g);let w=await O(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(w)}});if(n&&t.kind==="supervisor-integrate"){let h=await Ab({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await fl({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=m.state;return{state:v,supervisorState:h,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:m.parentAdvance,continuation:L(v)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||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 m=zN().captureExecutionIdentity({identityProvider:Et,executionRef:eD("builder")}),v=await Qb({paths:e.paths,name:e.name,input:{identity:m,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let g=await cf({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=g.checks.filter(({status:R})=>R==="failed").map(({id:R})=>R),k=g.checks.filter(({status:R})=>R==="interrupted").map(({id:R})=>R),b=t.verification_checks.filter(({id:R,repeatable:y})=>k.includes(R)&&!y).map(({id:R})=>R);if(w.length>0||b.length>0){let R=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${b.join(", ")}`,y=await ea({paths:e.paths,name:e.name,reason:R,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:y,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},requestChecks:null,verifierDispatch:null,continuation:L(y)}}return{state:g.state,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},continuationCheckPlans:t.verification_checks,...k.length>0?{continuationRetryCheckIds:k}:{},requestChecks:null,verifierDispatch:null,continuation:L(g.state,void 0,{...k.length>0?{retryCheckIds:k}:{verificationCheckPlans:t.verification_checks}})}}return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(v)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let h=await O(e.paths,e.name);Hl(h);let m=await Xb({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks.filter(({status:g})=>g==="interrupted").map(({id:g})=>g);if(v.length>0){let w=((await lt(G(e.paths,e.name)))?.checks??[]).filter(({id:k,status:b,executionCount:R})=>v.includes(k)&&b==="interrupted"&&R>=3).map(({id:k})=>k);if(w.length>0){let k=await ea({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:k,checks:m.checks,requestChecks:null,verifierDispatch:null,continuation:L(k)}}}return{state:m.state,checks:m.checks,...v.length>0?{continuationRetryCheckIds:v}:{},requestChecks:null,verifierDispatch:null,continuation:L(m.state,void 0,{retryCheckIds:v.length>0?v:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let h=await O(e.paths,e.name);if(h.builder_handoff!==null&&h.builder_handoff.identity_provider!==Et){let b=await ea({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:b,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(b)}}Hl(h);let m=await cf({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks,g=v.filter(({status:b})=>b==="interrupted").map(({id:b})=>b);if(g.length>0){let b=t.checks.filter(({id:y,repeatable:S})=>g.includes(y)&&!S).map(({id:y})=>y);if(b.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${b.join(", ")}`);let R=await O(e.paths,e.name);return{state:R,checks:v,runtimeCheckExecution:{disposition:m.disposition},continuationRetryCheckIds:g,requestChecks:null,verifierDispatch:null,continuation:L(R,void 0,{retryCheckIds:g})}}let w=eD("verifier"),k=await Zb({paths:e.paths,name:e.name,checks:v,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:k,checks:v,runtimeCheckExecution:{disposition:m.disposition},requestChecks:null,verifierDispatch:rD({paths:e.paths,state:k,checks:v,verifierExecutionRef:w,supervisor:a?n:null}),continuation:L(k,void 0,{verifierExecutionRef:w})}}if(t.kind==="verifier-started"){let h=await ek({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(h)}}if(t.kind==="verifier-execution-error"){let h=await O(e.paths,e.name);Hl(h),await XS({paths:e.paths,state:h});let m=await rk({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(m)}}if(t.kind==="verifier-unavailable"){let h=await ik({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:h.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:L(h)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await O(e.paths,e.name),c=Hl(s),l=await XS({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=zN(),d=u.captureExecutionIdentity({identityProvider:Et,executionRef:l}),f=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let h=await J(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared before final verification");f=ws(h)}let p=await tk({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:v})=>v!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let h=f??await J(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared during verification");let m=ys(h,p.state);return await oe(e.paths,m),{...p,supervisorState:m,verifierDispatch:null,continuation:L(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:rD({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await XS({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:L(p.state,void 0,{verifierExecutionRef:l})}}as();uc();var u8=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function d8(e){let t=Pe(e,"--expected-state-version"),r=Pe(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new I("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new I("--expected-state-version must be a positive integer");if(!u8.has(r))throw new I("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function da(e,t,r,i,n){let a=await ns({paths:e,name:t.name});a.local&&(r??=qc(t,a.local),i===void 0&&(i=dl(a.local,a.local.workspace.projectRoot)));let o=await nt({paths:e,state:t}),s=o?.confirmed?await J(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:d})=>d?[d.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:d})=>d==="interrupted").map(({id:d})=>d):void 0;return{...o?{childSummary:o.children.reduce((d,f)=>({...d,[f.status]:(d[f.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:L(t,o,{verifierExecutionRef:r,verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function f8(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function aD(e){return{action:e.action,reason:e.reason,message:e.message}}async function sD(e,t){let r=at(e,"change name"),i=Pe(e,"--summary"),n=Pe(e,"--runner-input"),a=Tt(e,"--validate-only"),o=Tt(e,"--confirmed"),s=Tt(e,"--accept-result"),c=Tt(e,"--revise-implementation"),l=Tt(e,"--revise-requirements"),u=Tt(e,"--retry-verifier"),d=Tt(e,"--resolve-verifier-blocker"),f=Pe(e,"--coordination-mode"),p=f;if(f!==void 0&&!Oh.includes(f))throw new I("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new I("--validate-only requires --runner-input");let h=Pe(e,"--max-parallel"),m=h===void 0?2:Number(h);if(!Number.isSafeInteger(m)||m<1)throw new I("--max-parallel must be a positive integer");let v=d8(e);if([o,s,c,l,u,d].filter(Boolean).length>1)throw new I("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(p!==void 0&&(o||s||c||l||u||d||n!==void 0))throw new I("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");$e(e);let g=await yr(t),w=await ta(g.paths,r);if(!await Ae(g.paths,r)){if(w){let C={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",action:"archive",commandArgs:w.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:w.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the Git blocker; do not treat this change as complete until it succeeds."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:w.result,continuation:C},error:{code:"conflict",message:w.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new I("--runner-input is only valid for portable Native changes");if(!i)throw new I("--summary is required");let P=await Bi({paths:g.paths,name:r});return V("next",{state:kt(P,g.paths),migration:{completed:!0,summary:i},continuation:L(P)})}let k=await O(g.paths,r);if(a){if(i||o||s||c||l||u||d||v||p!==void 0)throw new I("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let P;try{P=await QS(n,t)}catch(C){return{...Rl("next",C),data:{state:kt(k,g.paths),continuation:L(k)}}}try{await ZS({paths:g.paths,name:r,state:k,input:P,projectRoot:t})}catch(C){return{...Rl("next",C),data:{state:kt(k,g.paths),continuation:L(k)}}}return V("next",{validation:{valid:!0,kind:P.kind},state:kt(k,g.paths),continuation:L(k)})}if(n!==void 0||!i||k.phase==="verify"||k.phase==="archive"||k.verification_result==="pass"){let P=wk(g.paths,k);if(P)return oD(g.paths,k,r,P)}if(n){if(i||o||s||c||l||u||d||p!==void 0||v)throw new I("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let P;try{P=await QS(n,t),await ZS({paths:g.paths,name:r,state:k,input:P,projectRoot:t}),k.document_constraints_version===1&&await av({paths:g.paths,state:k})}catch(Ee){return{...Rl("next",Ee),data:{state:kt(k,g.paths),continuation:L(k)}}}let C=await hv({paths:g.paths,name:r});if(C.action==="rerun-final-verification")return V("next",{state:kt(C.state,g.paths),...await da(g.paths,C.state)});let x=await Rs({paths:g.paths,name:r,preserveRunningExecution:!0}),D=x.state;if(x.action==="await-user"||x.action==="done"||x.reason!=="available")return V("next",{state:kt(D,g.paths),recovery:aD(x),...await da(g.paths,D)});if(D.phase==="build"){let Ee=await Mi({paths:g.paths,state:D});if(Ee.drifted){let F=await Ns({paths:g.paths,name:r,reason:Ee.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return V("next",{state:kt(F,g.paths),...await da(g.paths,F)})}let Ni=await J(g.paths,r),Ir=await nt({paths:g.paths,state:D});if(Ir&&!Ir.allDone&&!Ni)throw new I("Native parent Build advances child changes and does not accept a Builder handoff")}let se=await nD({paths:g.paths,name:r,input:P,maxVerifyFailures:g.config.native.max_verify_failures}),U="continuationCheckPlans"in se?se.continuationCheckPlans:void 0,Le="continuationRetryCheckIds"in se?se.continuationRetryCheckIds:void 0;return V("next",{...f8(se),state:kt(se.state,g.paths),...await da(g.paths,se.state,se.verifierDispatch?.verifierExecutionRef,U,Le),coordination:Et})}if(!i)throw new I("--summary is required");let R=await hv({paths:g.paths,name:r});if(R.action==="rerun-final-verification")return V("next",{state:kt(R.state,g.paths),...await da(g.paths,R.state)});let y=await Rs({paths:g.paths,name:r}),S=y.state;if(y.reason==="workspace-mismatch")return oD(g.paths,S,r,y.message);if(p!==void 0&&S.phase!=="shape")throw new I("--coordination-mode is only valid when confirming Shape");let E,N=null;if(o)if(S.phase==="shape"&&S.status==="await-user"&&S.loop.next_action==="confirm-shape"){if(!v)throw new I("--expected-state-version and --expected-action are required for Shape confirmation");E=await Jb({paths:g.paths,name:r,expectedContinuation:v})}else{if(S.phase==="shape")throw new I("--confirmed is only valid from the persisted Shape user confirmation boundary");if(S.phase==="verify"&&S.status==="await-user"&&S.loop.next_action==="confirm-verifier-unavailable")E=await nk({paths:g.paths,name:r,summary:i,expectedContinuation:v});else throw new I("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!v&&(S.phase!=="verify"||S.status!=="await-user"||S.loop.next_action!=="confirm-skill-coordinated-pass"))throw new I("--accept-result is only valid for a pending Verify pass decision");E=await sk({paths:g.paths,name:r,expectedContinuation:v})}else if(c){if(S.phase!=="verify")throw new I("--revise-implementation is only valid from Verify");E=await ea({paths:g.paths,name:r,reason:i,expectedContinuation:v})}else if(l){if(!v&&S.phase!=="verify"&&S.phase!=="archive")throw new I("--revise-requirements is only valid from Verify or Archive");E=await Ns({paths:g.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:v})}else if(u)E=await ok({paths:g.paths,name:r,expectedContinuation:v});else if(d)E=await ak({paths:g.paths,name:r,reason:i,expectedContinuation:v});else{if(y.reason!=="available"){let D=((await nt({paths:g.paths,state:S}))?.confirmed?await J(g.paths,S.name,{diagnostics:!0}):null)?.children.flatMap(({task:se})=>se?[Ua(se,S.name,g.paths.projectRoot)]:[])??[];return V("next",{state:kt(S,g.paths),recovery:aD(y),...await da(g.paths,S),...D.length>0?{supervisorTasks:D}:{}})}if(S.phase==="build"){let C=await Mi({paths:g.paths,state:S});if(C.drifted)E=await Ns({paths:g.paths,name:r,reason:C.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let x=await nt({paths:g.paths,state:S});if(x){let D=x,se=[],U=[],Le=null,Ee=await J(g.paths,r);if(Ee&&!x.allDone){let Ni=await Ib({paths:g.paths,parent:r,maxParallel:S.coordination_mode==="single-session"?1:m});se=Ni.state.children.flatMap(({task:Ir})=>Ir?[Ua(Ir,r,g.paths.projectRoot)]:[]),Le=Ni.tasks.map(({child:Ir})=>Ir),U=Ni.state.children.flatMap(({name:Ir,blocker:F})=>F?[{child:Ir,message:F}]:[]),(se.length>0||Ni.state.stateVersion!==Ee.stateVersion)&&(D=await nt({paths:g.paths,state:S})??D)}if(D.allDone&&!(S.loop.stage==="repairing"&&S.verification_result==="fail"))N=await fl({paths:g.paths,name:r,trigger:"recovery"}),E=N.state;else return V("next",{state:kt(S,g.paths),childSummary:D.children.reduce((Ni,Ir)=>({...Ni,[Ir.status]:(Ni[Ir.status]??0)+1}),{total:D.children.length}),readyChildren:Le??D.readyChildren,...se.length>0?{supervisorTasks:se}:{},...U.length>0?{supervisorBlockers:U}:{},continuation:L(S,D)})}}}if(S.phase==="shape"&&(E=await Bb({paths:g.paths,name:r,enforceDocumentConstraints:!0,...p===void 0?{}:{coordinationMode:p},expectedContinuation:v})),E)return V("next",{state:kt(E,g.paths),...N?{parentAdvance:N.parentAdvance}:{},...await da(g.paths,E)});let P=S.phase==="shape"?await nt({paths:g.paths,state:S}):null;return{command:"next",exitCode:65,data:{state:kt(S,g.paths),continuation:L(S,P)},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 V("next",{state:kt(E,g.paths),...p===void 0?{}:{coordinationMode:p},...await da(g.paths,E)})}async function oD(e,t,r,i){let n=L(t),a=t.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 V("next",{state:kt(t,e),...await da(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}ot();Z();async function cD(e,t){let r=at(e,"root subcommand");if(r==="show"){$e(e);let i=await te(t);if(!i)throw new Error(".comet/config.yaml was not found");let n=await Se(t,i.native.artifact_root);return V("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=at(e,"artifact root");$e(e);let n=await FO({projectRoot:t,toArtifactRoot:i});return V("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
365
|
-
`)}throw new I(`Unknown root command: ${r}`)}import fa from"node:path";import{realpathSync as p8}from"node:fs";Qe();ot();Z();var h8=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Vf(e,t){let r=fa.normalize(eE(e)),i=fa.normalize(eE(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function eE(e){let t=fa.resolve(e);try{return p8.native(t)}catch{return t}}function m8(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function lD(e,t){let r=[];for(let i of await SS(e))t!==void 0&&i!==t||r.push({name:i,kind:await Ae(e,i)?"portable":"legacy"});return r}async function pD(e,t){let r=fa.resolve(e),i=Hs(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>Vf(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>fa.resolve(l)).sort()){let l=Vf(c,r)?r:c,u=eE(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let f=await te(l);if(!f)continue;let p=await Se(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:p,gitContext:gg(l,i)??ie(l),changes:await lD(p,t)})}if(o.length===0){let c=await te(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Se(e,c.native.artifact_root);o.push({projectRoot:fa.resolve(e),config:c,paths:l,gitContext:gg(e,i)??ie(e),changes:await lD(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await dT(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await ta(c.paths,t,{onError:l})].filter(u=>u!==null):await kv(c.paths,{onError:l})}return o}function uD(e,t){return e.workspace.bindingState==="aligned"?0:Vf(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function hD(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,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])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:d,kind:f})=>{let p=d.finishJournalErrors?.find(({name:h})=>h===n);if(f==="portable")try{let h=await O(d.paths,n);return{source:d,name:n,kind:f,workspace:cg(d.paths,h,d.gitContext),portableStatus:null,inspectionError:p?.message??null,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}}catch(h){return{source:d,name:n,kind:f,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:h instanceof Error?h.message:String(h)}}return{source:d,name:n,kind:f,workspace:a.length>1?await od(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:p?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:f})=>f.name===n).map(f=>{let p=TS({paths:d.paths,...f,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null});return{source:d,name:n,kind:"portable",workspace:p.workspace,portableStatus:p,inspectionError:d.finishJournalErrors?.find(({name:h})=>h===n)?.message??null,record:f,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[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}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(p=>p.finishJournals?.some(({name:h})=>h===n)),f=d?.finishJournals?.find(({name:p})=>p===n);if(d&&f){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:f.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:f.result?.message??"Native workspace finish record is orphaned."},finishJournal:f});continue}}if(s.length>0){for(let f of o)if(f.kind==="portable")try{f.record=await gf(f.source.paths,fa.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(f=>[...o,...s.filter(p=>!pT(f.record,p.record))].every(p=>p.record&&fT(f.record,p.record)));if(d){i.push(d);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((d,f)=>uD(d,e)-uD(f,e)||d.source.projectRoot.localeCompare(f.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>Qr.maxChanges)throw new Error(`Native status discovery exceeds ${Qr.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function dD(e,t){let r=t.toString(36),i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function v8(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=h8.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=j("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 fD(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?m8(r):null,nextPageArgs:r}}async function g8(e,t,r){let i=await od(e.source.paths,e.name),n=null;try{n=await is(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:xl(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 tE(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:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,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");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return TS({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Ar({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return tE({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return g8(e,t,r)}async function hg(e){let{sources:t,candidates:r}=await mD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>Vf(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),xl(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})}return e.onSelectedRoot?.(r[0].source.projectRoot),tE(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function mD(e,t){let r=await pD(e,t),i=(await hD(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}async function vD(e){let{sources:t,candidates:r}=await mD(e.projectRoot,e.name);return r.length>0?r[0].source.projectRoot:(t.find(i=>Vf(i.projectRoot,e.projectRoot))??t[0]).projectRoot}async function gD(e){let t=await pD(e.projectRoot),r=await hD(e.projectRoot,t),i=j("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=v8({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+Qr.maxItems).map(u=>tE(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?dD(i,f):null,h={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...fD(fa.resolve(e.projectRoot),p),limits:{...Qr}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Qr.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?dD(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...fD(fa.resolve(e.projectRoot),l),limits:{...Qr}}}async function wD(e,t){let r=at(e,"change name");$e(e),await yr(t);let i=t,n=await hg({projectRoot:t,name:r,onSelectedRoot:a=>{i=a}});return await mv((await yr(i)).paths,r),{...V("select",{selected:r,...n}),executionCwd:i}}Ht();import{promises as yD}from"fs";import ND from"path";Ht();ci();Fe();cr();Bn();Z();var bD=jv.maxSpecs*4;async function w8(e,t){let r=ND.join(pe(e,t),"specs"),i;try{i=await qr({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 yD.opendir(r);try{for await(let s of o){if(a+=1,a>bD)throw new Error(`Native proposed specs directory exceeds ${bD} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Tn(s.name);let c=ND.join(r,s.name,"spec.md");await T(e.nativeRoot,c);let l;try{l=await yD.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>jv.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 kD(e,t){let r=pe(e,t),i={};for(let n of await w8(e,t)){let a=await z({root:r,ref:`specs/${n}/spec.md`,maxBytes:null});i[n]=a.text}return i}Z();async function SD(e,t){let r=at(e,"change name");$e(e);let i=await vD({projectRoot:t,name:r}),{paths:n}=await yr(i);if(await Ae(n,r)){let d=await ns({paths:n,name:r}),f=d.state,p=X(n,r),h=await z({root:p,ref:f.brief,maxBytes:null,includeHash:!1}),m=[];for(let g of f.spec_changes){if(g.source===null)continue;let w=await z({root:p,ref:g.source,maxBytes:null,includeHash:!1});m.push({capability:g.capability,operation:g.operation,source:g.source,content:w.text})}let v={state:f,artifacts:_i(n,f.name),brief:h.text,proposedSpecs:m,continuation:L(f,await nt({paths:n,state:f}),{verifierExecutionRef:qc(f,d.local),...d.local?{verificationCheckPlans:dl(d.local,d.local.workspace.projectRoot)}:{}})};return{...V("show",v),executionCwd:i}}let a=await di(n,r);if(a.status==="migration-required")return{...V("show",{name:r,artifacts:_i(n,r),schema:a.schema,minimumRuntimeVersion:a.minimumRuntimeVersion,migrationRequired:!0,message:a.message}),executionCwd:i};if(a.status!=="current"||!a.state)throw new Fr(a.schema,a.minimumRuntimeVersion);let o=a.state,s=pe(n,r),c=await kD(n,r),l=await z({root:s,ref:o.brief,maxBytes:null}),u={state:o,artifacts:_i(n,o.name),brief:l.text,proposedSpecs:c};if(Buffer.byteLength(JSON.stringify(u),"utf8")>Y$)throw new Error("Native show output exceeds its serialized byte budget");return{...V("show",u),executionCwd:i}}import{promises as ED}from"node:fs";import y8 from"node:path";async function RD(e,t){let r=at(e,"spec subcommand");if(r==="sync"){let s=Pe(e,"--input"),c=at(e,"change name"),l=at(e,"capability");if($e(e),!s)throw new I("spec sync requires --input <json-file>");let u=y8.resolve(t,s),d=await ED.lstat(u).catch(()=>{throw new I(`Spec sync input file is unreadable: ${s}`)});if(!d.isFile()||d.isSymbolicLink()||d.size>1024*1024)throw new I("Spec sync input must be a bounded regular JSON file");let f;try{f=JSON.parse(await ED.readFile(u,"utf8"))}catch{throw new I("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(m=>typeof m=="string")||!Array.isArray(f.replacements)||!f.replacements.every(m=>m&&typeof m=="object"&&Object.keys(m).sort().join(",")==="from,to"&&typeof m.from=="string"&&typeof m.to=="string"))throw new I("Spec sync input fields are invalid");let{paths:p}=await yr(t),h=await Vb({...f,paths:p,name:c,capability:l});return V("spec sync",{...h,continuation:L(h)},`Synced Native spec references in ${c}
|
|
362
|
+
`)}ot();Oe();import{promises as Z3}from"node:fs";import fg from"node:path";Ht();Xs();_n();Fo();import{createHash as F0}from"node:crypto";import{promises as Ol}from"node:fs";import Dt from"node:path";fr();import{createHash as a3}from"node:crypto";import{AsyncLocalStorage as o3}from"node:async_hooks";var s3=new o3;function c3(e,t){let r=Ed(e),i=t.runGit??_,n=s3.getStore(),a=n?.active?n.observations:void 0,o=a?.get(r)?.get(i);if(o)return o;let s=r;try{let l=i(r,["remote","get-url","origin"]).trim();if(l)s=l;else throw new Error("No origin")}catch{try{let l=i(r,["rev-parse","--git-common-dir"]).trim();l&&(s=Ed(r,l))}catch{}}let c={identity:S0(s),name:d3(s)};if(a){let l=a.get(r)??new Map;l.set(i,c),a.set(r,l)}return c}function l3(e,t={}){return c3(e,t).identity}function u3(e){let t=S0(e),i=(t.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",n=a3("sha256").update(t,"utf8").digest("hex").slice(0,8);return`${i.slice(0,40)}-${n}`}function k0(e,t={}){return u3(l3(e,t))}function d3(e){return(e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-zA-Z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project"}function S0(e){let t=e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return t||"project"}var ua=class extends Error{code;constructor(t,r,i){super(r,i),this.name="BoundedHttpRequestError",this.code=t}};async function f3(e,t){if(!e.body){let s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>t)throw new ua("response-too-large","HTTP response exceeds byte limit");return s}let r=e.body.getReader(),i=[],n=0;try{for(;;){let s=await r.read();if(s.done)break;if(n+=s.value.byteLength,n>t)throw await r.cancel(),new ua("response-too-large","HTTP response exceeds byte limit");i.push(s.value)}}finally{r.releaseLock()}let a=new Uint8Array(n),o=0;for(let s of i)a.set(s,o),o+=s.byteLength;return a}async function E0(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs);try{let i=await(e.fetch??globalThis.fetch)(e.url,{...e.init,signal:t.signal}),n=i.ok?await f3(i,e.maxResponseBytes):new Uint8Array;return{response:i,bytes:n}}catch(i){throw i instanceof ua?i:t.signal.aborted?new ua("timeout","HTTP request timed out",{cause:i}):new ua("request-failed","HTTP request failed",{cause:i})}finally{clearTimeout(r)}}import R0 from"node:path";var p3=/^[a-z0-9][a-z0-9._-]{1,127}$/u,_0=2e3,h3=1024,m3=32,v3=32,g3=32,w3=16,y3=16,A0=32,N3=128,b3=32,k3=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),S3=new Set(["trial","proven","enforced","superseded"]),E3=new Set(["automatic","user","repository"]),R3=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function $l(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Zr(e,t,r=_0){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e.trim()}function LS(e,t){let r=Zr(e,t,128);if(!p3.test(r))throw new Error(`${t} must use a stable record id`);return r}function Tl(e,t,r,i){if(e===void 0)return[];if(!Array.isArray(e)||e.length>r)throw new Error(`${t} must be a bounded list`);return e.map((n,a)=>i(n,a))}function I0(e,t,r,i){if(!Array.isArray(e)||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty bounded list`);return e.map((n,a)=>i(n,a))}function BS(e,t){let r=Zr(e,t,h3).replaceAll("\\","/");if(R0.posix.isAbsolute(r)||R0.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(i=>i===".."))throw new Error(`${t} must be a project-relative path`);return r}function P3(e,t,r=m3){return Tl(e,t,r,(i,n)=>BS(i,`${t}[${n}]`))}function P0(e,t,r=v3){return Tl(e,t,r,(i,n)=>Zr(i,`${t}[${n}]`,512))}function MS(e,t,r=_0){if(e!==void 0)return Zr(e,t,r)}function x0(e,t){if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer`);return Number(e)}function Ff(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer`);return Number(e)}function j0(e,t){let r=$l(e,t),i=r.lineStart,n=r.lineEnd,a=i===void 0?void 0:x0(i,`${t}.lineStart`),o=n===void 0?void 0:x0(n,`${t}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${t}.lineEnd must be greater than or equal to lineStart`);let s=MS(r.anchor,`${t}.anchor`,256),c=MS(r.evidence,`${t}.evidence`,1024);return{source:BS(r.source,`${t}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function x3(e,t){let r=$l(e,`conclusions[${t}]`);return{text:Zr(r.text,`conclusions[${t}].text`),sources:I0(r.sources,`conclusions[${t}].sources`,A0,(i,n)=>j0(i,`conclusions[${t}].sources[${n}]`))}}function C3(e,t){let r=$l(e,`relations[${t}]`),i=Zr(r.type,`relations[${t}].type`,64);if(!R3.has(i))throw new Error(`relations[${t}].type is unsupported`);return{type:i,targetId:LS(r.targetId,`relations[${t}].targetId`),sources:I0(r.sources,`relations[${t}].sources`,A0,(n,a)=>j0(n,`relations[${t}].sources[${a}]`))}}function _3(e,t){let r=$l(e,`verification[${t}]`),i=MS(r.expected,`verification[${t}].expected`);return{command:Zr(r.command,`verification[${t}].command`),...i===void 0?{}:{expected:i}}}function A3(e,t){let r=$l(e,`sourceVersions[${t}]`),i=r.digest;if(i!==void 0&&(typeof i!="string"||!/^[a-f0-9]{64}$/u.test(i)))throw new Error(`sourceVersions[${t}].digest must be a SHA-256 hash`);return{source:BS(r.source,`sourceVersions[${t}].source`),size:Ff(r.size,`sourceVersions[${t}].size`),modifiedAt:Ff(r.modifiedAt,`sourceVersions[${t}].modifiedAt`),...i===void 0?{}:{digest:i}}}function I3(e,t){return e.reduce((r,i)=>r+i.sources.length,0)+t.reduce((r,i)=>r+i.sources.length,0)}function C0(e){let t=Zr(e,"updatedAt",64);if(Number.isNaN(Date.parse(t)))throw new Error("updatedAt must be an ISO-8601 timestamp");return t}function j3(e){let t=$l(e,"record"),r=Zr(t.type,"type",64);if(!k3.has(r))throw new Error("type is unsupported");let i=Zr(t.state,"state",32);if(!S3.has(i))throw new Error("state is unsupported");let n=Zr(t.authority,"authority",32);if(!E3.has(n))throw new Error("authority is unsupported");let a=Tl(t.conclusions,"conclusions",g3,x3),o=Tl(t.relations,"relations",w3,C3);if(I3(a,o)>N3)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Tl(t.sourceVersions,"sourceVersions",b3,A3);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:LS(t.id,"id"),projectId:LS(t.projectId,"projectId"),type:r,state:i,authority:n,title:Zr(t.title,"title"),summary:Zr(t.summary,"summary"),applicablePaths:P3(t.applicablePaths,"applicablePaths"),operations:P0(t.operations,"operations"),phases:P0(t.phases,"phases"),conclusions:a,relations:o,verification:Tl(t.verification,"verification",y3,_3),sourceVersions:s,applicationCount:Ff(t.applicationCount,"applicationCount"),successCount:Ff(t.successCount,"successCount"),failureCount:Ff(t.failureCount,"failureCount"),...t.lastAppliedAt===void 0?{}:{lastAppliedAt:C0(t.lastAppliedAt)},updatedAt:C0(t.updatedAt)}}function Eo(e){return j3(e)}var T3=1024*1024,$3=512,D0=200,H0=1600,O3=5e3,D3=8,H3=512*1024,F3=32;function xe(e,t,r=!1){if(typeof e!="string")return null;let i=[...e].map(n=>{let a=n.codePointAt(0)??0;return a<32||a===127?" ":n}).join("").trim().slice(0,t);return r&&!i?null:i}function WS(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;let r=xe(t.code,64,!0),i=xe(t.message,240,!0);return r&&i?{code:r,message:i}:null}).filter(t=>t!==null).slice(0,D3):[]}function qf(){return[]}function T0(e){let t={...e};return delete t.evidence,t}function $0(e){return{...e,conclusions:e.conclusions.map(t=>({...t,sources:t.sources.map(T0)})),relations:e.relations.map(t=>({...t,sources:t.sources.map(T0)}))}}function q3(e){if(e.kind==="upsert")return{kind:"upsert",record:$0(e.record)};if(e.kind!=="experience-delta")return e;let t=e.delta,r=t.payload;r?.kind==="record"?r={kind:"record",record:$0(Eo(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:xe(r.projectId,128)??"",commands:Lf(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:i,...n}=t,a={...n,statement:xe(t.statement,4e3)??"",...t.title===void 0?{}:{title:xe(t.title,512)??""},applicability:{...t.applicability.projectId===void 0?{}:{projectId:xe(t.applicability.projectId,128)??""},...t.applicability.paths===void 0?{}:{paths:Lf(t.applicability.paths,32,512)},...t.applicability.operations===void 0?{}:{operations:Lf(t.applicability.operations,16,128)},...t.applicability.phases===void 0?{}:{phases:Lf(t.applicability.phases,16,128)},...t.applicability.tasks===void 0?{}:{tasks:Lf(t.applicability.tasks,16,512)}},evidence:t.evidence.slice(0,F3).map(o=>({...o,summary:xe(o.summary,1e3)??"",...o.source===void 0?{}:{source:xe(o.source,512)??""},...o.anchor===void 0?{}:{anchor:xe(o.anchor,256)??""},...o.command===void 0?{}:{command:xe(o.command,2e3)??""}})),...r===void 0?{}:{payload:r}};return{...e,idempotencyKey:xe(e.idempotencyKey,256,!0)??"invalid",delta:a}}function Lf(e,t,r){return Array.isArray(e)?e.map(i=>xe(i,r)).filter(i=>!!i).slice(0,t):[]}function L3(e){if(e.kind==="search"){let t=e.query;return{kind:"search",task:xe(t.task,2e3)??"",...t.path?{path:xe(t.path,512)}:{},...t.phase?{phase:xe(t.phase,128)}:{},...t.operation?{operation:xe(t.operation,128)}:{},terms:t.terms.slice(0,28).map(r=>xe(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,e.limit??8))}}return e.kind==="list"?{kind:"list",...e.projectId?{projectId:xe(e.projectId,128)}:{},...e.type?{type:e.type}:{},...e.state?{state:e.state}:{},...e.authority?{authority:e.authority}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="manifest"?{kind:"manifest",...e.projectId?{projectId:xe(e.projectId,128)}:{},...e.state?{state:e.state}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="expand"?{kind:"expand",id:xe(e.id,128)??"",...e.projectId?{projectId:xe(e.projectId,128)}:{}}:{kind:"get",id:xe(e.id,128)??"",...e.projectId?{projectId:xe(e.projectId,128)}:{}}}function VS(e,t,r){if(!Array.isArray(e))return[];let i=[];for(let n of e.slice(0,500))try{let a=Eo(n);if(a.projectId!==r)throw new Error("Project mismatch");i.push(a)}catch{t()}return i}function M3(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return t(),null;let i=xe(e.content,H0,!0),n=xe(e.source,$3,!0);if(!i||!n)return t(),null;let a=e.title,o=a===void 0?void 0:xe(a,D0);if(a!==void 0&&o===null)return t(),null;let s=e.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return t(),null;let c,l=e.record;if(l!==void 0)try{if(c=Eo(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return t(),null}return{content:i,source:n,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function B3(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)&&"status"in e?e.status:e;if(!r||typeof r!="object"||Array.isArray(r))return t(),null;let i=r.provider,n=r.healthy,a=r.writable;if(i!=="remote"||typeof n!="boolean"||typeof a!="boolean")return t(),null;let o=r.recordCount,s=r.updatedAt;return{provider:"remote",healthy:n,writable:a,...Number.isSafeInteger(o)&&Number(o)>=0?{recordCount:Number(o)}:{},...typeof s=="string"?{updatedAt:s.slice(0,64)}:{},diagnostics:WS(r.diagnostics)}}function V3(e,t,r,i){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.kind??t.kind,o=WS(n.diagnostics);if(a==="list")return{kind:"list",records:VS(n.records,r,i),truncated:n.truncated===!0,diagnostics:o};if(a==="get"){let f=n.record,p=null;if(f!=null)try{if(p=Eo(f),p.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:p,diagnostics:o}}if(a==="expand"){let f=n.record,p=null;if(f!=null)try{if(p=Eo(f),p.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:p,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(n.items)?n.items.slice(0,500).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];let h=p,m=xe(h.id,128,!0),v=xe(h.title,D0,!0),g=xe(h.summary,H0,!0),w=h.type,k=h.memoryType,b=h.state,R=h.authority;if(!m||!v||!g||!["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"].includes(String(w))||k!=="project-model"&&k!=="project-policy"||!["trial","proven","enforced","superseded"].includes(String(b))||!["automatic","user","repository"].includes(String(R)))return r(),[];let y=E=>Array.isArray(E)?E.map(N=>xe(N,1024)).filter(N=>N!==null):[],S=Array.isArray(h.verification)?h.verification.slice(0,16).flatMap(E=>{if(!E||typeof E!="object"||Array.isArray(E))return r(),[];let N=xe(E.command,4e3,!0),P=xe(E.expected,2e3);return N?[{command:N,...P===null?{}:{expected:P}}]:[]}):[];return[{id:m,memoryType:k,type:w,state:b,authority:R,title:v,summary:g,applicablePaths:y(h.applicablePaths),operations:y(h.operations),phases:y(h.phases),sourceTypes:y(h.sourceTypes),verification:S}]}):[],truncated:n.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let f of Array.isArray(n.results)?(n.results??[]).slice(0,16):[]){let p=M3(f,r,i);if(!(!p||l.has(`${p.source}\0${p.title??""}`))){if(c+p.content.length>O3)break;l.add(`${p.source}\0${p.title??""}`),c+=p.content.length,s.push(p)}}let u=VS(n.records,r,i);return{kind:"search",hits:Array.isArray(n.hits)?(n.hits??[]).slice(0,40).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];try{let p=Eo(f.record);if(p.projectId!==i)throw new Error("Project mismatch");let h=f.score;return h!==void 0&&(typeof h!="number"||!Number.isFinite(h))?(r(),[]):[{record:p,...h===void 0?{}:{score:h}}]}catch{return r(),[]}}):u.map(f=>({record:f})),results:s,records:u,truncated:n.truncated===!0,diagnostics:o}}function W3(e,t,r,i){let n=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.record,o;if(a===null)o=null;else if(a!==void 0)try{if(o=Eo(a),o.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:t.kind,changed:n.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(n.records)?{records:VS(n.records,r,i)}:{},diagnostics:WS(n.diagnostics)}}var dg=class{options;projectId;constructor(t){this.options=t,this.projectId=t.projectId??(t.projectRoot?k0(t.projectRoot):"project")}async status(){let t=this.options.config.token_env;if(t&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${t}。`};return this.report(a.code,a.message),{provider:"remote",healthy:!1,writable:!1,diagnostics:[a]}}let r=await this.request("status",{});if(r===null)return{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let i={value:!1},n=B3(r,()=>{i.value=!0});return!n||i.value?(this.report("remote-schema","Remote Project Knowledge status 响应格式无效。"),{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge status 响应格式无效。"}]}):n}async query(t){let r=t.kind==="search"?this.projectId:t.projectId??this.projectId,i=await this.request("query",L3(t),t.kind==="search"?void 0:t.projectId);if(i===null)return O0(t);let n={value:!1},a=V3(i,t,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),O0(t)):a}async apply(t){let r=(t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId)??this.projectId,i=await this.request("apply",q3(t),t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId);if(i===null)return{kind:t.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},a=W3(i,t,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:t.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(t,r,i=this.projectId){let n=this.options.config.token_env,a=this.token();if(n&&!a)return this.report("remote-token",`Remote Project Knowledge 未配置环境变量 ${n}。`),null;let o={schema:"comet.project-knowledge.provider.v1",operation:t,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:xe(i,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>H3)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await E0({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:T3,fetch:this.options.fetch,init:{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:s}});if(!c.ok)return this.report("remote-status",`Remote Project Knowledge 返回 HTTP ${c.status}。`),null;try{let u=JSON.parse(new TextDecoder().decode(l));return z3(u,t,o.projectId)?u.result:(this.report("remote-schema","Remote Project Knowledge 响应 envelope 无效。"),null)}catch{return this.report("remote-json","Remote Project Knowledge 返回了无效 JSON。"),null}}catch(c){return this.report("remote-failed",c instanceof ua&&c.code==="timeout"?"Remote Project Knowledge 请求超时。":"Remote Project Knowledge 请求失败。"),null}}report(t,r){this.options.reportDiagnostic?.({code:t,message:r})}token(){let t=this.options.config.token_env;return t?this.options.env?.[t]??process.env[t]:void 0}};function z3(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;let i=e;return i.schema==="comet.project-knowledge.provider.v1"&&i.operation===t&&i.projectId===r&&Object.prototype.hasOwnProperty.call(i,"result")}function O0(e){return e.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:qf()}:e.kind==="get"?{kind:"get",record:null,diagnostics:qf()}:e.kind==="expand"?{kind:"expand",record:null,diagnostics:qf()}:e.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:qf()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:qf()}}var q0=512,zS=256*1024,M0=8*1024*1024,J3=2e3,B0=Dt.join(".comet","runtime","native","capability-discovery-cache.json"),Mf="comet.native.capability-cache.v1",V0=512*1024,W0=32;function JS(e,t){let r=Dt.relative(Dt.resolve(e),Dt.resolve(t));return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}function G3(e,t){return Dt.relative(e,t).replaceAll(Dt.sep,"/")}function K3(e,t,r){e?.({code:t,message:r})}async function U3(e,t){if(!JS(t,e))return!1;try{let r=await Ol.lstat(e);return!r.isDirectory()||r.isSymbolicLink()?!1:JS(await Ol.realpath(t),await Ol.realpath(e))}catch{return!1}}async function KS(e){let t=Dt.resolve(e.projectRoot),r=Date.now()+J3,i=[],n=!0,a=0,o=async(c,l)=>{if(Date.now()>r){n=!1;return}if(!await U3(c,t))return;let u=async d=>{if(Date.now()>r||i.length>=q0){n=!1;return}let f;try{f=await Ol.readdir(d,{withFileTypes:!0})}catch{n=!1;return}for(let p of f.sort((h,m)=>h.name.localeCompare(m.name,"en"))){if(Date.now()>r){n=!1;return}if(p.isSymbolicLink())continue;let h=Dt.join(d,p.name);if(p.isDirectory()){await u(h);continue}if(!p.isFile()||!p.name.toLowerCase().endsWith(".md")||!JS(t,h))continue;let m=await Ol.stat(h);if(m.size>zS)continue;if(a+m.size>M0){n=!1;return}if(Date.now()>r){n=!1;return}let v=G3(t,h),g;try{g=await Wt(t,v,zS,{label:`${l} capability Spec`})}catch{n=!1;continue}if(a+=g.bytes.length,i.push({absolutePath:h,source:v,kind:l,size:m.size,mtimeMs:m.mtimeMs,contentHash:F0("sha256").update(g.bytes).digest("hex")}),i.length>=q0){n=!1;return}}};await u(c)};await o(Dt.resolve(t,...e.scope.currentSpecRoot.split("/")),"native-spec"),await o(Dt.resolve(t,...e.scope.archiveRoot.split("/")),"native-archive"),i.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=F0("sha256").update(JSON.stringify(i.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})))).digest("hex");return n||K3(e.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:i,fingerprint:s,complete:n}}function L0(e){return/^(?:#)\s+(.+)$/mu.exec(e)?.[1]?.trim()}function Y3(e,t,r){let i=`${t}
|
|
363
|
+
${e}`.toLocaleLowerCase();return r.reduce((n,a)=>n+(i.includes(a.toLocaleLowerCase())?1:0),0)}var GS=class{constructor(t,r,i){this.projectRoot=t;this.manifest=r;this.reportDiagnostic=i}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(t){if(t.kind!=="search")throw new Error("Native capability discovery only supports search queries");let r=[],i=[],n=0;for(let a of this.manifest.sources){if(n+a.size>M0){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await Wt(this.projectRoot,a.source,zS,{label:`${a.kind} capability Spec`});n+=o.bytes.length;let s=o.bytes.toString("utf8"),c=Y3(s,a.source,t.query.terms);if(c===0)continue;let l={absolutePath:a.absolutePath,source:a.source,kind:a.kind};i.push({content:s,source:a.source,...L0(s)?{title:L0(s)}:{},score:c,document:l})}catch(o){let s={code:"capability-corpus-read",message:`能力候选来源无法读取,已跳过 ${a.source}:${o instanceof Error?o.message:String(o)}`};r.push(s),this.reportDiagnostic?.(s)}}return i.sort((a,o)=>o.score-a.score||a.source.localeCompare(o.source)),{kind:"search",hits:[],results:i,records:[],truncated:!this.manifest.complete,diagnostics:r}}async apply(t){throw new Error("Native capability discovery is read-only")}};async function z0(e){let r=(await Ho(e.projectRoot))?.knowledge;if(r?.provider==="remote"){if(!r.remote)throw new Error("Configured remote Project Knowledge provider is missing remote settings");return new dg({config:r.remote,projectRoot:e.projectRoot,...e.reportDiagnostic?{reportDiagnostic:e.reportDiagnostic}:{}})}let i=await KS(e);return new GS(Dt.resolve(e.projectRoot),i,e.reportDiagnostic)}function J0(e){return JSON.stringify({workflow:e.scope.workflow,currentSpecRoot:e.scope.currentSpecRoot,archiveRoot:e.scope.archiveRoot,task:e.task.trim()})}function X3(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.workflow==="native"&&(t.query===null||typeof t.query=="object"&&t.query!==null)&&Array.isArray(t.candidates)&&t.candidates.length<=5&&(t.associationDraft===null||typeof t.associationDraft=="object"&&t.associationDraft!==null)&&Array.isArray(t.diagnostics)&&typeof t.searched=="boolean"&&t.providerLimit===40}function Q3(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema!==Mf||!Array.isArray(t.entries)||t.entries.length>W0)return null;let r=[];for(let i of t.entries){if(!i||typeof i!="object"||Array.isArray(i))return null;let n=i;if(typeof n.key!="string"||typeof n.fingerprint!="string"||!X3(n.result))return null;r.push({key:n.key,fingerprint:n.fingerprint,result:n.result})}return{schema:Mf,entries:r}}async function G0(e){try{let t=await Ol.readFile(Dt.join(e,B0),"utf8");return Buffer.byteLength(t,"utf8")>V0?null:Q3(JSON.parse(t))}catch{return null}}async function K0(e){let t=Dt.resolve(e.projectRoot);if((await Ho(t))?.knowledge?.provider==="remote")return null;let i=await KS({projectRoot:t,scope:e.scope});return i.complete?(await G0(t))?.entries.find(o=>o.key===J0(e)&&o.fingerprint===i.fingerprint)?.result??null:null}async function U0(e){let t=Dt.resolve(e.projectRoot);if((await Ho(t))?.knowledge?.provider==="remote")return;let i=await KS({projectRoot:t,scope:e.scope});if(!i.complete)return;let n=await G0(t)??{schema:Mf,entries:[]},a=J0(e),o=[{key:a,fingerprint:i.fingerprint,result:e.result},...n.entries.filter(l=>!(l.key===a&&l.fingerprint===i.fingerprint))].slice(0,W0),s=JSON.stringify({schema:Mf,entries:o});if(Buffer.byteLength(s,"utf8")>V0)return;let{atomicWriteJson:c}=await Promise.resolve().then(()=>(Oe(),lE));await c(Dt.join(t,B0),{schema:Mf,entries:o},{containedRoot:Dt.join(t,".comet","runtime","native")})}Z();ls();async function e8(e){let t=await z({root:e.paths.specsDir,ref:`${e.capability}/spec.md`,maxBytes:null,includeHash:!1}),r=e.capability.split("/"),i=X(e.paths,e.changeName),n=`specs/${e.capability}/spec.md`,a=`specs/${e.capability}/delta.yaml`;await Z3.mkdir(fg.join(i,"specs",...r),{recursive:!0}),await Ne(fg.join(i,...n.split("/")),t.text,{containedRoot:e.paths.nativeRoot});let o=rt(t.text),s=th(t.text),c={schema:"comet.native.delta.v1",capability:e.capability,base_hash:o,base_version:1,legacy_hash:jo(t.text),base_requirements:Object.fromEntries(s.requirements.map(l=>[l.id,rt(l.raw)])),operations:[]};return await Ne(fg.join(i,...a.split("/")),eh(c),{containedRoot:e.paths.nativeRoot}),{specSource:n,deltaSource:a,baseHash:o}}async function t8(e,t,r,i){if(!r&&!i)return null;let n=[],a={workflow:"native",currentSpecRoot:`${t}/comet/specs`,archiveRoot:`${t}/comet/archive`};try{if(r&&!i){let l=await K0({projectRoot:e,scope:a,task:r});if(l)return l}let o=i?void 0:await z0({projectRoot:e,scope:a,reportDiagnostic:l=>n.push(l)}),s=await uj({projectRoot:e,scope:a,...o?{provider:o}:{},...r?{task:r}:{},...i?{capability:i}:{}}),c={...s,diagnostics:[...n,...s.diagnostics]};return r&&!i&&await U0({projectRoot:e,scope:a,task:r,result:c}),c}catch(o){if(i)throw o;return{workflow:"native",query:null,candidates:[],associationDraft:null,diagnostics:[...n,{code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${o instanceof Error?o.message:String(o)}`}],searched:!!r,providerLimit:40}}}async function Y0(e,t){let r=at(e,"change name"),i=await te(t),n=Jv(e,i?.native.language??"en"),a=Pe(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new I("--isolation must be current, branch, or worktree");let o=Pe(e,"--change-branch"),s=Pe(e,"--target-branch"),c=Pe(e,"--worktree-path"),l=Pe(e,"--task"),u=Pe(e,"--capability");$e(e);let d=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let f=await Td({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:d});t=f.projectRoot,i=await te(t);let p=i===null?Mo("docs",n):void 0;if(i||(i=p),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let h=await Se(t,i.native.artifact_root);await wh(h),await Qu(t);let m=await t8(t,i.native.artifact_root,l,u),v=await Mb({paths:h,name:r,language:n,workspaceBinding:f.binding,...p?{initialProjectConfig:p}:{}}),g,w;return m?.associationDraft&&(w=await e8({paths:h,changeName:v.name,capability:m.associationDraft.capability}),g=fg.join(X(h,v.name),"capability-association.yaml"),await Ne(g,dj(m.associationDraft),{containedRoot:h.nativeRoot})),await mv(h,v.name),p&&await Lm(t),{executionCwd:t,...V("new",{...v,artifacts:_i(h,v.name),preparation:f.preparation,...m===null?{}:{capabilityDiscovery:m,...g===void 0?{}:{associationPath:g},...w===void 0?{}:{deltaProposal:w}},continuation:L(v)},`Created Native change ${v.name}
|
|
364
|
+
`)}}Pm();ls();fr();import{randomUUID as iD}from"node:crypto";import{promises as X0}from"node:fs";import Bf from"node:path";Vc();Pb();gd();Fe();as();function Fl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function me(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 Dl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>me(r,`${t}[${i}]`))}function r8(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Fl(t,`Native Builder check ${r}`);if(qe(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${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:me(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function pg(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Fl(t,`Native Runtime check ${r}`);if(qe(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${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:me(i.id,`Native Runtime check ${r} id`),name:me(i.name,`Native Runtime check ${r} name`),executable:me(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:me(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Q0(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:me(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function i8(e){let t=Fl(e,"Native Supervisor evidence");return qe(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:me(t.summary,"Native Supervisor evidence summary"),checks:Dl(t.checks,"Native Supervisor evidence checks"),acceptance:_m(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:me(t.receiptRef,"Native Supervisor receipt ref")}}}function n8(e){let t=Fl(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),qe(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=Fl(t.review,"Native Builder review");if(qe(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:me(n.summary,"Native Builder review summary"),reviewer_execution_ref:me(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:me(t.summary,"Native Builder summary"),addressed_acceptance_ids:Dl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:r8(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:pg(t.verification_checks)}:{},known_limits:Dl(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return qe(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:pg(t.checks)};if(t.kind==="retry-checks")return qe(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:Dl(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return qe(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:me(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:me(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:vd(t.response,"/response")};if(t.kind==="verifier-started")return qe(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:me(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:me(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return qe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:me(t.summary,"Native Verifier execution error summary"),...Q0(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return qe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:me(t.summary,"Native unavailable Verifier summary"),...Q0(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return qe(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),candidateCommit:me(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return qe(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),reason:me(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(qe(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:me(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return qe(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return qe(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),reason:me(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(qe(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:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:i8(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(qe(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:me(t.child,"Native Supervisor child"),runId:me(t.runId,"Native Supervisor runId"),checks:pg(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Dl(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=Fl(i,"Native Supervisor material");return qe(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:me(a.name,"Native Supervisor material name"),content:me(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return qe(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:me(t.child,"Native Supervisor child"),checks:pg(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Dl(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function QS(e,t){let r=Bf.resolve(t,e),i=await X0.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(wf(await X0.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return n8(n)}function a8(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function o8(e){return e.kind.startsWith("supervisor-")}function s8(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function Z0(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function US(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function c8(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function YS(e){let t=await lt(G(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function ZS(e){let t=await mn({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await J(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await nt({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(o8(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&a8(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(c8(e.state,e.input.addressed_acceptance_ids),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&&Wr(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(Z0(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");Wr(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(Z0(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await lt(G(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(d=>d.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){US(e.state);let c=await YS({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");Wr(o,s8(e.input));return}if(e.input.kind==="verifier-started"){US(e.state);let c=await YS({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){US(e.state);let c=await YS({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<Mn)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Wr(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Wr(r.integration.worktree,c.checks)}}function eD(e){return`${Et}:${e}:${iD()}`}function tD(e,t,r,i){if(Bf.resolve(_(e.projectRoot,["rev-parse","--show-toplevel"]))!==Bf.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(_(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!zr(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(_(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{_(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 l8(e,t){let r=ie(e.projectRoot),i=Bf.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Bf.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=_(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!zr(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{_(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 Hl(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Et)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function u8(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function rD(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Hl(r),s=u8(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Et,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:X(t,r.name),supervisorStateRef:a?ss(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,scopeCount:c.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,runtimeChecks:i.map(l=>({...l})),builderReportedChecks:o.checks.map(l=>({...l})),builderKnownLimits:o.known_limits.map(l=>({...l})),startupInstruction:'As this Verifier, submit the startup receipt first: save {"kind":"verifier-started","candidateId":"<candidateId above>","verifierExecutionRef":"<verifierExecutionRef above>"} as a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It only records that this Verifier actually started; a repeat submission is accepted without side effects. Then read the scenarios and proceed.',evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function XS(e){Hl(e.state);let t=await lt(G(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 nD(e){let t=e.input,r=await O(e.paths,e.name),i=await mn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await J(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:h})=>h==="integrated"||h==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:h})=>h==="integrated"||h==="archived");if(n&&t.kind==="supervisor-checks"){let h=await Rb({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await J(e.paths,e.name),v=m?.children.find(({name:g})=>g===t.child)?.task;return{state:r,supervisorState:m,supervisorTask:v&&v.runId===t.runId?Ua(v,e.name,e.paths.projectRoot):null,checks:[],checkExecution:h,requestChecks:null,verifierDispatch:null,continuation:L(r)}}if(n&&t.kind==="supervisor-builder-result")return A(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:b})=>b===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{tD(m.task,t.candidateCommit,"builder",`comet/supervisor/${h.parent}/${t.child}`)}catch(b){throw await oe(e.paths,kd(h,{child:t.child,runId:t.runId,reason:b.message})),b}let v=m.task.projectRoot,g=UN(h,t),w=bd(g,{role:"verifier",child:t.child,projectRoot:v,runId:iD()});await oe(e.paths,w.state);let k=await O(e.paths,e.name);return{state:k,supervisorTask:Ua(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:L(k)}});if(n&&t.kind==="supervisor-builder-failure")return A(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let v=Am(h,{child:t.child,runId:t.runId,reason:t.reason});await oe(e.paths,v);let g=await O(e.paths,e.name);return{state:g,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(g)}});if(n&&t.kind==="supervisor-retry-builder")return A(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=XN(h,{child:t.child,expectedStateVersion:t.stateVersion});await oe(e.paths,m);let v=await O(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(v)}});if(n&&t.kind==="supervisor-reconnect")return A(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child)?.task;if(!m||m.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{l8(m,`comet/supervisor/${h.parent}/${t.child}`)}catch(w){throw await oe(e.paths,kd(h,{child:t.child,runId:t.runId,reason:w.message})),w}let v=KN(h,{child:t.child,runId:t.runId});await oe(e.paths,v.state);let g=await O(e.paths,e.name);return{state:g,supervisorState:v.state,supervisorTask:Ua(v.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:L(g)}});if(n&&t.kind==="supervisor-cancel")return A(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=Am(h,{child:t.child,runId:t.runId,reason:t.reason});await oe(e.paths,m);let v=await O(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(v)}});if(n&&t.kind==="supervisor-verifier-result")return A(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let h=await J(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:k})=>k===t.child);if(!m?.task||m.task.role!=="verifier"||!m.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{tD(m.task,m.candidateCommit,"verifier",`comet/supervisor/${h.parent}/${t.child}`)}catch(k){throw await oe(e.paths,kd(h,{child:t.child,runId:t.runId,reason:k.message})),k}let v=t.evidence.receiptRef||t.verdict==="pass"?await il({paths:e.paths,parent:e.name,task:m.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!v||v.checks.some(({status:k,exitCode:b})=>k!=="passed"||b!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=YN(h,{...t,evidence:{...t.evidence,checks:v?.checks.map(({name:k,status:b})=>`${k}: ${b}`)??[],execution:structuredClone(m.task)}});await oe(e.paths,g);let w=await O(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(w)}});if(n&&t.kind==="supervisor-integrate"){let h=await Ab({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await fl({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=m.state;return{state:v,supervisorState:h,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:m.parentAdvance,continuation:L(v)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||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 m=zN().captureExecutionIdentity({identityProvider:Et,executionRef:eD("builder")}),v=await Qb({paths:e.paths,name:e.name,input:{identity:m,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let g=await cf({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=g.checks.filter(({status:R})=>R==="failed").map(({id:R})=>R),k=g.checks.filter(({status:R})=>R==="interrupted").map(({id:R})=>R),b=t.verification_checks.filter(({id:R,repeatable:y})=>k.includes(R)&&!y).map(({id:R})=>R);if(w.length>0||b.length>0){let R=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${b.join(", ")}`,y=await ea({paths:e.paths,name:e.name,reason:R,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:y,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},requestChecks:null,verifierDispatch:null,continuation:L(y)}}return{state:g.state,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},continuationCheckPlans:t.verification_checks,...k.length>0?{continuationRetryCheckIds:k}:{},requestChecks:null,verifierDispatch:null,continuation:L(g.state,void 0,{...k.length>0?{retryCheckIds:k}:{verificationCheckPlans:t.verification_checks}})}}return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(v)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let h=await O(e.paths,e.name);Hl(h);let m=await Xb({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks.filter(({status:g})=>g==="interrupted").map(({id:g})=>g);if(v.length>0){let w=((await lt(G(e.paths,e.name)))?.checks??[]).filter(({id:k,status:b,executionCount:R})=>v.includes(k)&&b==="interrupted"&&R>=3).map(({id:k})=>k);if(w.length>0){let k=await ea({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:k,checks:m.checks,requestChecks:null,verifierDispatch:null,continuation:L(k)}}}return{state:m.state,checks:m.checks,...v.length>0?{continuationRetryCheckIds:v}:{},requestChecks:null,verifierDispatch:null,continuation:L(m.state,void 0,{retryCheckIds:v.length>0?v:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let h=await O(e.paths,e.name);if(h.builder_handoff!==null&&h.builder_handoff.identity_provider!==Et){let b=await ea({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:b,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(b)}}Hl(h);let m=await cf({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks,g=v.filter(({status:b})=>b==="interrupted").map(({id:b})=>b);if(g.length>0){let b=t.checks.filter(({id:y,repeatable:S})=>g.includes(y)&&!S).map(({id:y})=>y);if(b.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${b.join(", ")}`);let R=await O(e.paths,e.name);return{state:R,checks:v,runtimeCheckExecution:{disposition:m.disposition},continuationRetryCheckIds:g,requestChecks:null,verifierDispatch:null,continuation:L(R,void 0,{retryCheckIds:g})}}let w=eD("verifier"),k=await Zb({paths:e.paths,name:e.name,checks:v,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:k,checks:v,runtimeCheckExecution:{disposition:m.disposition},requestChecks:null,verifierDispatch:rD({paths:e.paths,state:k,checks:v,verifierExecutionRef:w,supervisor:a?n:null}),continuation:L(k,void 0,{verifierExecutionRef:w})}}if(t.kind==="verifier-started"){let h=await ek({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(h)}}if(t.kind==="verifier-execution-error"){let h=await O(e.paths,e.name);Hl(h),await XS({paths:e.paths,state:h});let m=await rk({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:L(m)}}if(t.kind==="verifier-unavailable"){let h=await ik({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:h.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:L(h)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await O(e.paths,e.name),c=Hl(s),l=await XS({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=zN(),d=u.captureExecutionIdentity({identityProvider:Et,executionRef:l}),f=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let h=await J(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared before final verification");f=ws(h)}let p=await tk({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:v})=>v!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let h=f??await J(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared during verification");let m=ys(h,p.state);return await oe(e.paths,m),{...p,supervisorState:m,verifierDispatch:null,continuation:L(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:rD({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await XS({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:L(p.state,void 0,{verifierExecutionRef:l})}}as();uc();var d8=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function f8(e){let t=Pe(e,"--expected-state-version"),r=Pe(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new I("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new I("--expected-state-version must be a positive integer");if(!d8.has(r))throw new I("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function da(e,t,r,i,n){let a=await ns({paths:e,name:t.name});a.local&&(r??=qc(t,a.local),i===void 0&&(i=dl(a.local,a.local.workspace.projectRoot)));let o=await nt({paths:e,state:t}),s=o?.confirmed?await J(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:d})=>d?[d.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:d})=>d==="interrupted").map(({id:d})=>d):void 0;return{...o?{childSummary:o.children.reduce((d,f)=>({...d,[f.status]:(d[f.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:L(t,o,{verifierExecutionRef:r,verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function p8(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function aD(e){return{action:e.action,reason:e.reason,message:e.message}}async function sD(e,t){let r=at(e,"change name"),i=Pe(e,"--summary"),n=Pe(e,"--runner-input"),a=Tt(e,"--validate-only"),o=Tt(e,"--confirmed"),s=Tt(e,"--accept-result"),c=Tt(e,"--revise-implementation"),l=Tt(e,"--revise-requirements"),u=Tt(e,"--retry-verifier"),d=Tt(e,"--resolve-verifier-blocker"),f=Pe(e,"--coordination-mode"),p=f;if(f!==void 0&&!Oh.includes(f))throw new I("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new I("--validate-only requires --runner-input");let h=Pe(e,"--max-parallel"),m=h===void 0?2:Number(h);if(!Number.isSafeInteger(m)||m<1)throw new I("--max-parallel must be a positive integer");let v=f8(e);if([o,s,c,l,u,d].filter(Boolean).length>1)throw new I("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(p!==void 0&&(o||s||c||l||u||d||n!==void 0))throw new I("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");$e(e);let g=await yr(t),w=await ta(g.paths,r);if(!await Ae(g.paths,r)){if(w){let C={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",action:"archive",commandArgs:w.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:w.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the Git blocker; do not treat this change as complete until it succeeds."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:w.result,continuation:C},error:{code:"conflict",message:w.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new I("--runner-input is only valid for portable Native changes");if(!i)throw new I("--summary is required");let P=await Bi({paths:g.paths,name:r});return V("next",{state:kt(P,g.paths),migration:{completed:!0,summary:i},continuation:L(P)})}let k=await O(g.paths,r);if(a){if(i||o||s||c||l||u||d||v||p!==void 0)throw new I("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let P;try{P=await QS(n,t)}catch(C){return{...Rl("next",C),data:{state:kt(k,g.paths),continuation:L(k)}}}try{await ZS({paths:g.paths,name:r,state:k,input:P,projectRoot:t})}catch(C){return{...Rl("next",C),data:{state:kt(k,g.paths),continuation:L(k)}}}return V("next",{validation:{valid:!0,kind:P.kind},state:kt(k,g.paths),continuation:L(k)})}if(n!==void 0||!i||k.phase==="verify"||k.phase==="archive"||k.verification_result==="pass"){let P=wk(g.paths,k);if(P)return oD(g.paths,k,r,P)}if(n){if(i||o||s||c||l||u||d||p!==void 0||v)throw new I("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let P;try{P=await QS(n,t),await ZS({paths:g.paths,name:r,state:k,input:P,projectRoot:t}),k.document_constraints_version===1&&await av({paths:g.paths,state:k})}catch(Ee){return{...Rl("next",Ee),data:{state:kt(k,g.paths),continuation:L(k)}}}let C=await hv({paths:g.paths,name:r});if(C.action==="rerun-final-verification")return V("next",{state:kt(C.state,g.paths),...await da(g.paths,C.state)});let x=await Rs({paths:g.paths,name:r,preserveRunningExecution:!0}),D=x.state;if(x.action==="await-user"||x.action==="done"||x.reason!=="available")return V("next",{state:kt(D,g.paths),recovery:aD(x),...await da(g.paths,D)});if(D.phase==="build"){let Ee=await Mi({paths:g.paths,state:D});if(Ee.drifted){let F=await Ns({paths:g.paths,name:r,reason:Ee.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return V("next",{state:kt(F,g.paths),...await da(g.paths,F)})}let Ni=await J(g.paths,r),Ir=await nt({paths:g.paths,state:D});if(Ir&&!Ir.allDone&&!Ni)throw new I("Native parent Build advances child changes and does not accept a Builder handoff")}let se=await nD({paths:g.paths,name:r,input:P,maxVerifyFailures:g.config.native.max_verify_failures}),U="continuationCheckPlans"in se?se.continuationCheckPlans:void 0,Le="continuationRetryCheckIds"in se?se.continuationRetryCheckIds:void 0;return V("next",{...p8(se),state:kt(se.state,g.paths),...await da(g.paths,se.state,se.verifierDispatch?.verifierExecutionRef,U,Le),coordination:Et})}if(!i)throw new I("--summary is required");let R=await hv({paths:g.paths,name:r});if(R.action==="rerun-final-verification")return V("next",{state:kt(R.state,g.paths),...await da(g.paths,R.state)});let y=await Rs({paths:g.paths,name:r}),S=y.state;if(y.reason==="workspace-mismatch")return oD(g.paths,S,r,y.message);if(p!==void 0&&S.phase!=="shape")throw new I("--coordination-mode is only valid when confirming Shape");let E,N=null;if(o)if(S.phase==="shape"&&S.status==="await-user"&&S.loop.next_action==="confirm-shape"){if(!v)throw new I("--expected-state-version and --expected-action are required for Shape confirmation");E=await Jb({paths:g.paths,name:r,expectedContinuation:v})}else{if(S.phase==="shape")throw new I("--confirmed is only valid from the persisted Shape user confirmation boundary");if(S.phase==="verify"&&S.status==="await-user"&&S.loop.next_action==="confirm-verifier-unavailable")E=await nk({paths:g.paths,name:r,summary:i,expectedContinuation:v});else throw new I("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!v&&(S.phase!=="verify"||S.status!=="await-user"||S.loop.next_action!=="confirm-skill-coordinated-pass"))throw new I("--accept-result is only valid for a pending Verify pass decision");E=await sk({paths:g.paths,name:r,expectedContinuation:v})}else if(c){if(S.phase!=="verify")throw new I("--revise-implementation is only valid from Verify");E=await ea({paths:g.paths,name:r,reason:i,expectedContinuation:v})}else if(l){if(!v&&S.phase!=="verify"&&S.phase!=="archive")throw new I("--revise-requirements is only valid from Verify or Archive");E=await Ns({paths:g.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:v})}else if(u)E=await ok({paths:g.paths,name:r,expectedContinuation:v});else if(d)E=await ak({paths:g.paths,name:r,reason:i,expectedContinuation:v});else{if(y.reason!=="available"){let D=((await nt({paths:g.paths,state:S}))?.confirmed?await J(g.paths,S.name,{diagnostics:!0}):null)?.children.flatMap(({task:se})=>se?[Ua(se,S.name,g.paths.projectRoot)]:[])??[];return V("next",{state:kt(S,g.paths),recovery:aD(y),...await da(g.paths,S),...D.length>0?{supervisorTasks:D}:{}})}if(S.phase==="build"){let C=await Mi({paths:g.paths,state:S});if(C.drifted)E=await Ns({paths:g.paths,name:r,reason:C.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let x=await nt({paths:g.paths,state:S});if(x){let D=x,se=[],U=[],Le=null,Ee=await J(g.paths,r);if(Ee&&!x.allDone){let Ni=await Ib({paths:g.paths,parent:r,maxParallel:S.coordination_mode==="single-session"?1:m});se=Ni.state.children.flatMap(({task:Ir})=>Ir?[Ua(Ir,r,g.paths.projectRoot)]:[]),Le=Ni.tasks.map(({child:Ir})=>Ir),U=Ni.state.children.flatMap(({name:Ir,blocker:F})=>F?[{child:Ir,message:F}]:[]),(se.length>0||Ni.state.stateVersion!==Ee.stateVersion)&&(D=await nt({paths:g.paths,state:S})??D)}if(D.allDone&&!(S.loop.stage==="repairing"&&S.verification_result==="fail"))N=await fl({paths:g.paths,name:r,trigger:"recovery"}),E=N.state;else return V("next",{state:kt(S,g.paths),childSummary:D.children.reduce((Ni,Ir)=>({...Ni,[Ir.status]:(Ni[Ir.status]??0)+1}),{total:D.children.length}),readyChildren:Le??D.readyChildren,...se.length>0?{supervisorTasks:se}:{},...U.length>0?{supervisorBlockers:U}:{},continuation:L(S,D)})}}}if(S.phase==="shape"&&(E=await Bb({paths:g.paths,name:r,enforceDocumentConstraints:!0,...p===void 0?{}:{coordinationMode:p},expectedContinuation:v})),E)return V("next",{state:kt(E,g.paths),...N?{parentAdvance:N.parentAdvance}:{},...await da(g.paths,E)});let P=S.phase==="shape"?await nt({paths:g.paths,state:S}):null;return{command:"next",exitCode:65,data:{state:kt(S,g.paths),continuation:L(S,P)},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 V("next",{state:kt(E,g.paths),...p===void 0?{}:{coordinationMode:p},...await da(g.paths,E)})}async function oD(e,t,r,i){let n=L(t),a=t.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 V("next",{state:kt(t,e),...await da(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}ot();Z();async function cD(e,t){let r=at(e,"root subcommand");if(r==="show"){$e(e);let i=await te(t);if(!i)throw new Error(".comet/config.yaml was not found");let n=await Se(t,i.native.artifact_root);return V("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=at(e,"artifact root");$e(e);let n=await FO({projectRoot:t,toArtifactRoot:i});return V("root move",n,`Moved Comet Native to ${n.toNativeRoot}
|
|
365
|
+
`)}throw new I(`Unknown root command: ${r}`)}import fa from"node:path";import{realpathSync as h8}from"node:fs";Qe();ot();Z();var m8=/^native-workspaces-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function Vf(e,t){let r=fa.normalize(eE(e)),i=fa.normalize(eE(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function eE(e){let t=fa.resolve(e);try{return h8.native(t)}catch{return t}}function v8(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function lD(e,t){let r=[];for(let i of await SS(e))t!==void 0&&i!==t||r.push({name:i,kind:await Ae(e,i)?"portable":"legacy"});return r}async function pD(e,t){let r=fa.resolve(e),i=Hs(e),n=i.map(({root:c})=>c),a=n.length>0?n:[r];a.some(c=>Vf(c,r))||a.push(r);let o=[],s=new Set;for(let c of a.map(l=>fa.resolve(l)).sort()){let l=Vf(c,r)?r:c,u=eE(l),d=process.platform==="win32"?u.toLowerCase():u;if(s.has(d))continue;s.add(d);let f=await te(l);if(!f)continue;let p=await Se(l,f.native.artifact_root);o.push({projectRoot:l,config:f,paths:p,gitContext:gg(l,i)??ie(l),changes:await lD(p,t)})}if(o.length===0){let c=await te(e);if(!c)throw new Error(".comet/config.yaml was not found in any registered worktree");let l=await Se(e,c.native.artifact_root);o.push({projectRoot:fa.resolve(e),config:c,paths:l,gitContext:gg(e,i)??ie(e),changes:await lD(l,t)})}for(let c of o){c.archiveErrors=[],c.finishJournalErrors=[],c.archives=await dT(c.paths,(u,d)=>c.archiveErrors.push({name:u,message:d}),t),t!==void 0&&(c.archives=c.archives.filter(({state:u})=>u.name===t),c.archiveErrors=c.archiveErrors.filter(({name:u})=>u===t));let l=(u,d)=>c.finishJournalErrors.push({name:u,message:d});c.finishJournals=t?[await ta(c.paths,t,{onError:l})].filter(u=>u!==null):await kv(c.paths,{onError:l})}return o}function uD(e,t){return e.workspace.bindingState==="aligned"?0:Vf(e.source.projectRoot,t)?1:e.workspace.bindingState==="legacy"?2:e.workspace.bindingState==="missing"?3:e.workspace.bindingState==="drifted"?4:5}async function hD(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,[]);for(let a of n.finishJournals??[])r.has(a.name)||r.set(a.name,[]);for(let a of n.finishJournalErrors??[])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:d,kind:f})=>{let p=d.finishJournalErrors?.find(({name:h})=>h===n);if(f==="portable")try{let h=await O(d.paths,n);return{source:d,name:n,kind:f,workspace:cg(d.paths,h,d.gitContext),portableStatus:null,inspectionError:p?.message??null,finishJournal:d.finishJournals?.find(({name:m})=>m===n)??null}}catch(h){return{source:d,name:n,kind:f,workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:"The portable state could not be inspected."},portableStatus:null,inspectionError:h instanceof Error?h.message:String(h)}}return{source:d,name:n,kind:f,workspace:a.length>1?await od(d.paths,n):{projectRoot:d.projectRoot,currentBranch:d.gitContext.currentBranch,isSecondaryWorktree:d.gitContext.isSecondaryWorktree,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:null,finish:null},portableStatus:null,inspectionError:p?.message??null}})),s=t.flatMap(d=>(d.archives??[]).filter(({state:f})=>f.name===n).map(f=>{let p=TS({paths:d.paths,...f,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null});return{source:d,name:n,kind:"portable",workspace:p.workspace,portableStatus:p,inspectionError:d.finishJournalErrors?.find(({name:h})=>h===n)?.message??null,record:f,finishJournal:d.finishJournals?.find(({name:h})=>h===n)??null}})),c=t.flatMap(d=>(d.archiveErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[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}let l=t.flatMap(d=>(d.finishJournalErrors??[]).filter(f=>f.name===n).map(f=>({source:d,error:f})))[0];if(l&&o.length===0&&s.length===0){i.push({source:l.source,name:n,kind:"portable",portableStatus:null,inspectionError:l.error.message,workspace:{projectRoot:l.source.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:l.error.message}});continue}if(o.length===0&&s.length===0){let d=t.find(p=>p.finishJournals?.some(({name:h})=>h===n)),f=d?.finishJournals?.find(({name:p})=>p===n);if(d&&f){i.push({source:d,name:n,kind:"portable",portableStatus:null,inspectionError:f.result?.message??"Native workspace finish journal has no matching active or archived change record.",workspace:{projectRoot:d.projectRoot,isolation:"current",bindingState:"mismatch",changeBranch:null,targetBranch:null,finish:null,message:f.result?.message??"Native workspace finish record is orphaned."},finishJournal:f});continue}}if(s.length>0){for(let f of o)if(f.kind==="portable")try{f.record=await gf(f.source.paths,fa.join(f.source.paths.changesDir,n,"comet-state.yaml"))}catch{}let d=s.find(f=>[...o,...s.filter(p=>!pT(f.record,p.record))].every(p=>p.record&&fT(f.record,p.record)));if(d){i.push(d);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((d,f)=>uD(d,e)-uD(f,e)||d.source.projectRoot.localeCompare(f.source.projectRoot));let u=o.filter(d=>d.workspace.bindingState==="aligned");u.length>1?i.push(...u):u.length===0&&o.length>1?i.push({...o[0],inspectionError:`Native change ${n} has conflicting workspace records and no aligned binding`}):i.push(u[0]??o[0])}if(i.length>Qr.maxChanges)throw new Error(`Native status discovery exceeds ${Qr.maxChanges} visible changes`);return i.sort((n,a)=>`${n.name}\0${n.source.projectRoot}`.localeCompare(`${a.name}\0${a.source.projectRoot}`))}function dD(e,t){let r=t.toString(36),i=j("comet.native.workspace-status-cursor.v1",{candidatesHash:e,offset:t});return`native-workspaces-v1.${e}.${r}.${i}`}function g8(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=m8.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=j("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 fD(e,t){let r=t?["comet","native","status","--cursor",t,"--project-root",e,"--json"]:null;return{nextPageCommand:r?v8(r):null,nextPageArgs:r}}async function w8(e,t,r){let i=await od(e.source.paths,e.name),n=null;try{n=await is(e.source.paths,e.name)}catch{}return n?.state?{schema:"comet.native.status.v2",name:e.name,phase:n.state.phase,status:"blocked",migrationRequired:!0,legacySchema:n.schema,workspace:i,continuation:{schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:n.state.phase,status:"blocked",disposition:"blocked",action:"none",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],message:"This change uses a legacy schema; the first mutating command performs the deterministic migration. Run the listed next command with a migration summary.",runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0}}}:xl(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 tE(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:[],message:`Run the repair command in the workspace holding this change: ${e.source.paths.projectRoot}`,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");if(!t&&e.portableStatus)return e.portableStatus;if(e.record?.state.archived)return TS({paths:e.source.paths,...e.record,finishJournal:e.finishJournal??null,details:t,cursor:i});try{return await Ar({paths:e.source.paths,name:e.name,details:t,gitContext:e.source.gitContext,...i?{cursor:i}:{}})}catch(n){if(i)throw n;return tE({...e,inspectionError:n instanceof Error?n.message:String(n)},!1)}}return w8(e,t,r)}async function hg(e){let{sources:t,candidates:r}=await mD(e.projectRoot,e.name);if(r.length===0){let i=t.find(n=>Vf(n.projectRoot,e.projectRoot))??t[0];return e.onSelectedRoot?.(i.projectRoot),xl(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})}return e.onSelectedRoot?.(r[0].source.projectRoot),tE(r[0],e.details??!1,e.acceptanceCursor,e.detailsCursor)}async function mD(e,t){let r=await pD(e,t),i=(await hD(e,r)).filter(n=>n.name===t);if(i.length>1)throw new Error(`Native change ${t} has multiple aligned workspace bindings: ${i.map(n=>n.source.projectRoot).join(", ")}`);return{sources:r,candidates:i}}async function vD(e){let{sources:t,candidates:r}=await mD(e.projectRoot,e.name);return r.length>0?r[0].source.projectRoot:(t.find(i=>Vf(i.projectRoot,e.projectRoot))??t[0]).projectRoot}async function gD(e){let t=await pD(e.projectRoot),r=await hD(e.projectRoot,t),i=j("comet.native.workspace-status-candidates.v1",r.map(u=>({name:u.name,projectRoot:u.source.projectRoot,bindingState:u.workspace.bindingState,kind:u.kind}))),n=g8({candidatesHash:i,total:r.length,cursor:e.cursor}),a=await Promise.all(r.slice(n,n+Qr.maxItems).map(u=>tE(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?dD(i,f):null,h={schema:s,total:r.length,offset:n,items:d,nextCursor:p,...fD(fa.resolve(e.projectRoot),p),limits:{...Qr}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Qr.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?dD(i,c):null;return{schema:s,total:r.length,offset:n,items:o,nextCursor:l,...fD(fa.resolve(e.projectRoot),l),limits:{...Qr}}}async function wD(e,t){let r=at(e,"change name");$e(e),await yr(t);let i=t,n=await hg({projectRoot:t,name:r,onSelectedRoot:a=>{i=a}});return await mv((await yr(i)).paths,r),{...V("select",{selected:r,...n}),executionCwd:i}}Ht();import{promises as yD}from"fs";import ND from"path";Ht();ci();Fe();cr();Bn();Z();var bD=jv.maxSpecs*4;async function y8(e,t){let r=ND.join(pe(e,t),"specs"),i;try{i=await qr({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 yD.opendir(r);try{for await(let s of o){if(a+=1,a>bD)throw new Error(`Native proposed specs directory exceeds ${bD} entries`);if(s.isSymbolicLink())throw new Error(`Proposed spec capability must not be a symbolic link: ${s.name}`);if(!s.isDirectory())continue;Tn(s.name);let c=ND.join(r,s.name,"spec.md");await T(e.nativeRoot,c);let l;try{l=await yD.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>jv.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 kD(e,t){let r=pe(e,t),i={};for(let n of await y8(e,t)){let a=await z({root:r,ref:`specs/${n}/spec.md`,maxBytes:null});i[n]=a.text}return i}Z();async function SD(e,t){let r=at(e,"change name");$e(e);let i=await vD({projectRoot:t,name:r}),{paths:n}=await yr(i);if(await Ae(n,r)){let d=await ns({paths:n,name:r}),f=d.state,p=X(n,r),h=await z({root:p,ref:f.brief,maxBytes:null,includeHash:!1}),m=[];for(let g of f.spec_changes){if(g.source===null)continue;let w=await z({root:p,ref:g.source,maxBytes:null,includeHash:!1});m.push({capability:g.capability,operation:g.operation,source:g.source,content:w.text})}let v={state:f,artifacts:_i(n,f.name),brief:h.text,proposedSpecs:m,continuation:L(f,await nt({paths:n,state:f}),{verifierExecutionRef:qc(f,d.local),...d.local?{verificationCheckPlans:dl(d.local,d.local.workspace.projectRoot)}:{}})};return{...V("show",v),executionCwd:i}}let a=await di(n,r);if(a.status==="migration-required")return{...V("show",{name:r,artifacts:_i(n,r),schema:a.schema,minimumRuntimeVersion:a.minimumRuntimeVersion,migrationRequired:!0,message:a.message}),executionCwd:i};if(a.status!=="current"||!a.state)throw new Fr(a.schema,a.minimumRuntimeVersion);let o=a.state,s=pe(n,r),c=await kD(n,r),l=await z({root:s,ref:o.brief,maxBytes:null}),u={state:o,artifacts:_i(n,o.name),brief:l.text,proposedSpecs:c};if(Buffer.byteLength(JSON.stringify(u),"utf8")>Y$)throw new Error("Native show output exceeds its serialized byte budget");return{...V("show",u),executionCwd:i}}import{promises as ED}from"node:fs";import N8 from"node:path";async function RD(e,t){let r=at(e,"spec subcommand");if(r==="sync"){let s=Pe(e,"--input"),c=at(e,"change name"),l=at(e,"capability");if($e(e),!s)throw new I("spec sync requires --input <json-file>");let u=N8.resolve(t,s),d=await ED.lstat(u).catch(()=>{throw new I(`Spec sync input file is unreadable: ${s}`)});if(!d.isFile()||d.isSymbolicLink()||d.size>1024*1024)throw new I("Spec sync input must be a bounded regular JSON file");let f;try{f=JSON.parse(await ED.readFile(u,"utf8"))}catch{throw new I("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(m=>typeof m=="string")||!Array.isArray(f.replacements)||!f.replacements.every(m=>m&&typeof m=="object"&&Object.keys(m).sort().join(",")==="from,to"&&typeof m.from=="string"&&typeof m.to=="string"))throw new I("Spec sync input fields are invalid");let{paths:p}=await yr(t),h=await Vb({...f,paths:p,name:c,capability:l});return V("spec sync",{...h,continuation:L(h)},`Synced Native spec references in ${c}
|
|
366
366
|
`)}if(r==="disassociate"){let s=at(e,"change name"),c=Pe(e,"--expected-state-version"),l=Pe(e,"--expected-action");if(c===void 0||l===void 0)throw new I("--expected-state-version and --expected-action are required for spec disassociate");if(!/^[1-9]\d*$/u.test(c)||!Number.isSafeInteger(Number(c)))throw new I("--expected-state-version must be a positive integer");if(l!=="disassociate-capability")throw new I("--expected-action for spec disassociate must be disassociate-capability");$e(e);let{paths:u}=await yr(t);if(!await Ae(u,s))throw new I("spec disassociate requires a current portable Native change");let d=await zb({paths:u,name:s,expectedContinuation:{stateVersion:Number(c),action:"disassociate-capability"}});return V("spec disassociate",{...d,continuation:L(d)},`Revoked Native capability association in ${s}
|
|
367
367
|
`)}if(r!=="remove")throw new I(`Unknown spec command: ${r}`);let i=at(e,"change name"),n=at(e,"capability");$e(e);let{paths:a}=await yr(t);await Ae(a,i)||await Bi({paths:a,name:i});let o=await Wb({paths:a,name:i,capability:n});return V("spec remove",{...o,continuation:L(o)},`Marked Native capability ${n} for removal in ${i}
|
|
368
|
-
`)}async function PD(e,t){let r=Tt(e,"--details"),i=Pe(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new I("status --details requires a change name");if(i&&n&&!r)throw new I("--cursor for a named status requires --details");$e(e);let a=t,o=n?await hg({projectRoot:t,name:n,onSelectedRoot:s=>{a=s},details:r,...i?{detailsCursor:i}:{}}):await gD({projectRoot:t,...i?{cursor:i}:{}});return{...V("status",o),executionCwd:a}}function iE(e,t){return t?{lifecycle:
|
|
368
|
+
`)}async function PD(e,t){let r=Tt(e,"--details"),i=Pe(e,"--cursor"),n=e[0]?.startsWith("--")?void 0:e.shift();if(r&&!n)throw new I("status --details requires a change name");if(i&&n&&!r)throw new I("--cursor for a named status requires --details");$e(e);let a=t,o=n?await hg({projectRoot:t,name:n,onSelectedRoot:s=>{a=s},details:r,...i?{detailsCursor:i}:{}}):await gD({projectRoot:t,...i?{cursor:i}:{}});return{...V("status",o),executionCwd:a}}function iE(e,t){return t?{lifecycle:k8(e),outcome:b8(e)}:{lifecycle:rE(),outcome:mg()}}function mg(){return{reviewResolved:!1,failureResolved:!1}}function b8(e){try{if(!e||typeof e!="object"||Array.isArray(e))return mg();let t=e,r=typeof t.change=="object"&&t.change!==null?t.change:t.state??t;if(!r||typeof r!="object"||Array.isArray(r))return mg();let i=r,n=i.verification&&typeof i.verification=="object"&&!Array.isArray(i.verification)?i.verification:{},a=n.verdict??i.verification_result,o=i.phase==="archive"&&a==="pass",s=Array.isArray(i.history)?i.history:[],c=i.learning&&typeof i.learning=="object"?i.learning:{},l=o&&(c.failureResolved===!0||s.some(d=>d!==null&&typeof d=="object"&&!Array.isArray(d)&&(d.outcome==="fail"||d.verdict==="fail"))),u=typeof n.summary=="string"?n.summary.trim():n.summary&&typeof n.summary=="object"&&typeof n.summary.text=="string"?n.summary.text.trim():typeof c.summary=="string"?c.summary.trim():typeof i.summary=="string"?i.summary.trim():void 0;return{reviewResolved:o,failureResolved:l,...u?{summary:u}:{}}}catch{return mg()}}function rE(){return{changedPaths:[],artifactRefs:[]}}function k8(e){try{if(!e||typeof e!="object"||Array.isArray(e))return rE();let t=e,r=n=>Array.isArray(n)?n.filter(a=>typeof a=="string").slice(0,24):[],i=typeof t.change=="object"&&t.change!==null?t.change:t.state??t;return{changedPaths:r(t.changedPaths),artifactRefs:r(t.artifactRefs??t.artifacts??i.learning?.artifactRefs)}}catch{return rE()}}var S8={"hook-guard":N0,init:b0,root:cD,new:Y0,spec:RD,show:SD,status:PD,select:wD,next:sD,archive:eO,check:sO,doctor:$S};async function E8(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=vS(o)}catch(c){throw new I(c.message)}return{command:s.topic?`${s.topic} --help`:"help",exitCode:0,data:s,text:s.usage}}let i=e.shift(),n=await X$(t),a=S8[i];if(!a)throw new I(`Unknown Native command: ${i}`);return{executionCwd:n,...await a(e,n)}}async function R8(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{Tt(i,"--json"),Tt(i,"--verbose"),s=Pe(i,"--project-root");let l=[...i,...n];c=l[0]??null;let u=await E8(l,s),d=wS(u,a,o);return{dispatch:u,output:d.output,experience:iE(u.data,d.structuredDataVisible),json:a,verbose:o}}catch(l){let u=Rl(c,l),d=wS(u,a,o);return{dispatch:u,output:d.output,experience:iE(u.data,d.structuredDataVisible),json:a,verbose:o}}}async function xD(e){return(await R8(e)).output}async function x8(e=process.argv.slice(2)){let t=await xD(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
|
|
369
369
|
`)?"":`
|
|
370
|
-
`)),t.exitCode}var CD=process.argv[1];CD&&import.meta.url===
|
|
370
|
+
`)),t.exitCode}var CD=process.argv[1];CD&&import.meta.url===P8(CD).href&&x8().then(e=>{process.exitCode=e});export{x8 as main};
|